Appearance
泛型
泛型是什么
泛型就是:先把类型空着,使用时再填具体类型。
c
List<int> scores;
List<string> names;
List<Enemy> enemies;这里的 List<T> 是一个通用列表模板。T 可以理解成“类型占位符”。 List<int> 表示这个列表只能放 int。 List<string> 表示这个列表只能放 string。 List<Enemy> 表示这个列表只能放 Enemy。
为什么要学泛型
它主要解决两个问题:
- 少写重复代码。
- 让编译器提前检查类型错误。
比如:
c
List<int> scores = new List<int>();
scores.Add(100);
scores.Add("hello"); // 错误:不能把 string 放进 List<int>这个错误会在编译时就发现,不会等游戏运行到一半才炸。
Unity 里最常见的泛型
你已经经常见到了:
c
Rigidbody rb = GetComponent<Rigidbody>();
Animator anim = GetComponent<Animator>();
List<Transform> spawnPoints;
Dictionary<string, int> itemCounts;GetComponent<Rigidbody>() 的意思是: “请从当前 GameObject 身上找一个 Rigidbody 组件,并按 Rigidbody 类型返回。”
泛型方法
c
void Show<T>(T value)
{
Debug.Log(value);
}
Show<int>(10);
Show("Player");第二个 Show("Player") 没写 <string>,因为编译器能从 "Player" 推断出 T 是 string。
泛型约束 where
如果你想要求 T 必须是 Unity 组件,可以写:
c
T GetOrAdd<T>() where T : Component
{
T component = GetComponent<T>();
if (component == null)
{
component = gameObject.AddComponent<T>();
}
return component;
}where T : Component 的意思是: T 不能随便填,必须是 Component 或它的子类,比如 Rigidbody、Animator、你写的 PlayerController。
初学记法
<T> 不是语法装饰,它是在告诉 C#: “这个类或方法里面有一个暂时没决定的类型,等使用时再确定。”
先掌握这三个就够你在 Unity 里用很久:
c
List<T>
Dictionary<TKey, TValue>
GetComponent<T>()参考链接