通常你會發現你不能修改正在使用的那些類,無論它是基礎的數據類型還是已有框架的一部分,它提供的方法讓你困苦不堪。不過。。C# 提供了一種巧妙的方式來讓你擴充已有的類,也就是我們今天要講的擴展方法。
擴展方法由於很方便而被經常使用到,我們更願意叫他語法糖豆(syntactic sugar),一個實用樣例是Unity的Transform類,比如:你只想設置Transform.position中Vector3的x軸,而其它兩個軸保持不變。
1
2
3
4
5
6
7
8
9
10
11
|
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
void Update ()
{
//Set new x position to 5
transform.position =
new
Vector3(5f, transform.position.y, transform.position.z);
}
}
|
在這個樣例中,如果你只設置Transform.position的x軸變量,編譯會報錯,所以你不得不把其余的y軸和z軸加上組成一個完整的Vector3。於是一個拓展方法比如SetPositionX() 就可以添加到Transform類中,從而讓代碼的可讀性更好。
為了創建拓展方法,你需要創建一個靜態類。此外,一個拓展方法的聲明前綴也必須加上靜態修飾符static,同時該方法的第一個參數為所操作的類型,且必須以this關鍵字修飾。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
using UnityEngine;
using System.Collections;
//Must be in a static class
public static class Extensions
{
//Function must be static
//First parameter has "this" in front of type
public static void SetPositionX(
this
Transform t, float newX)
{
t.position =
new
Vector3(newX, t.position.y, t.position.z);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
|
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
void Update ()
{
//Set new x position to 5
transform.SetPositionX(5f);
}
}
|
提示:拓展方法只能在實例中被調用,而不能在類本身內部使用。
這里有一些樣例代碼來幫你更好理解拓展方法,以作參考。
拓展:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
using UnityEngine;
using System.Collections;
public static class Extensions
{
public static void SetPositionX(
this
Transform t, float newX)
{
t.position =
new
Vector3(newX, t.position.y, t.position.z);
}
public static void SetPositionY(
this
Transform t, float newY)
{
t.position =
new
Vector3(t.position.x, newY, t.position.z);
}
public static void SetPositionZ(
this
Transform t, float newZ)
{
t.position =
new
Vector3(t.position.x, t.position.y, newZ);
}
public static float GetPositionX(
this
Transform t)
{
return
t.position.x;
}
public static float GetPositionY(
this
Transform t)
{
return
t.position.y;
}
public static float GetPositionZ(
this
Transform t)
{
return
t.position.z;
}
public static bool HasRigidbody(
this
GameObject gobj)
{
return
(gobj.rigidbody !=
null
);
}
public static bool HasAnimation(
this
GameObject gobj)
{
return
(gobj.animation !=
null
);
}
public static void SetSpeed(
this
Animation anim, float newSpeed)
{
anim[anim.clip.name].speed = newSpeed;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
void Update ()
{
//move x position 5 units
float currentX = transform.GetPositionX();
transform.SetPositionX(currentX + 5f);
if
(gameObject.HasRigidbody())
{
//Do something with physics!
}
if
(gameObject.HasAnimation())
{
//Double the animation speed!
gameObject.animation.SetSpeed(2f);
}
}
}
|
提示:靜態類不能拓展MonoBehaviour類。
提示:如果你是在某個命名空間內部定義的拓展方法,那么在調用時,你必須添加using指令以包含這個命名空間。