namespace test { // 泛型的协变,T 只能作为返回的参数 public interface Class1<out T> { T Get(); int Count { get; } } public class Class2 : Class1<String> { public String Get() { return ""; } public int Count { get { return 1; } } } // 泛型的抗变,T在方法中只能作为传入参数 public interface Class3<in T> { void Get(T t); // 作为参数 // T GetT();//报错 } public class Class4 : Class3<int> { public void Get(int age) { } } }
使用out(协变)可以实例化 子类,协变 : 可以让右边 用子类,让泛型更方便
不加 out 报错:
逆变 : 可以让右边 用父类,实例化父类
泛型委托
public delegate void delega<in T>(string name); static void get<T>(string name) { } static void Main(string[] args) { delega<int> delega = new delega<int>(get<int>); delega += new delega<int>(get<string>);