使用泛型(generic)
unity里还是很常见的,这里<>里填写你需要的类型。
例如:
// 拿到组件
GetComponent<Render>().sortingOrder = 0;
// 可排序对象
public class B : IComparable<B>
// 泛型集合,字典等
Dictionary<string, B> mydic = new Dictionary<string, B>();
// 等等
泛型的可以避免强转
c#2(版本)出现了泛型。在c#1时只能使用强转,例如在使用非泛型集合(ArrayList)的时候。如果强制转换了错误的类型……
下面代码在mylist位置3插入了另外的类型。
ArrayList mylist;
mylist = new ArrayList();
A a1 = new A();
myList.Add(a1);
A a2 = new A();
myList.Add(a2);
B b = new B();
myList.Add(b);// 竟然加入一个别的类型元素
for ( int i = 0; i < mylist.Count; i ++ )
{
A a = (A)mylist[i]; //强转骗过了编译器
a.DoSomething();
}
where关键字
where T :后面的内容可以限制T是什么。
public class SomeClass
{
public T GenericMethod<T>( T param ) where T : class
{
return param;
}
}
比较常见的where后面会跟:
class表示T是一个引用类型。可以使用null。
struct表示T是一个值类型。
new()表示T有个public的无参数的构造函数。
MonoBehavior(一个类)表示T是这个类。
IEnumerable(一个接口)表示T有这个接口的实现。
自己主动使用泛型
处理算法相似只是要处理的类型不同的时候,可以考虑把统一的算法用泛型来处理。
比如各种容器类(List、Array等)会碰到。
比如一个Line的封装,可以是2D或3D。这时写一个Line,可以是Line Line。
比如读取XML的一部分,如下:
public static void SetObjectValue<T>( T obj, string fieldname, object value )
{
System.Reflection.FieldInfo info = obj.GetType().GetField(fieldname);
if ( info != null )
{
info.SetValue(obj, value);
}
}
public class Player
{
public string name = string.Empty;
public int id = 0;
};
Player p = new Player();
SetObjectValue<Player>( p, "name", "tom" );
SetObjectValue<Player>( p, "level", 100 );
比如泛型委托,如下:
public class ImplementingClass
{
public float WhichIsBig( int a, float b )
{
if ( a > b )
return a;
else
return b;
}
}
public delegate float CallDelegate<T,S>( T t, S s );
CallDelegate<int, float> delegateBig = new CallDelegate<int, float>( new ImplementingClass().WhichIsBig );
float big = delegateBig( 10, 25.0f );