泛型的基础使用:
class Program{/// <summary>/// 系统自带的Action委托 可以有无参数 但是无返回值/// </summary>public static event Action mydelegate1;//当把委托加上event关键字的时候,事件只能在本类中被调用,其他类只能添加和删除事件内容public static Action<int, int> mydelegate2;//系统自带的Func委托 可以有无参数 必须有一个返回值,系统设定最后一位是它的返回值static Func<int> my3;static Func<int, int, int> my4;static void Main(string[] args){test();indexClass index = new indexClass();//实体类中泛型方法的调用var res = index.GetT<string, int>(1, "4");Console.ReadLine();}static async void test(){//匿名方法的写法mydelegate1 = delegate { Console.WriteLine("委托1"); };//lambda表达式的写法mydelegate2 = (s, d) => { Console.WriteLine($"{ s},{ d}委托2"); };my3 = () => { return 1; };my4 = delegate (int a, int b) { return a + b; };//委托的调用mydelegate1.Invoke();mydelegate2.Invoke(1, 2);int ae = my3.Invoke();Console.WriteLine(ae);int er = my4.Invoke(2, 3);Console.WriteLine(er);//这里的参数只写了两个一样的,因为这个类刚好满足了他们参数的约束indexClass2<Address, Address> indexClass2 = new indexClass2<Address, Address>();Console.WriteLine("执行完成");}}//当类不是泛型的时候 想要其中的某个方法是泛型,就是下面这个类class indexClass{public T GetT<T,V>(V id,T jj){Console.WriteLine(id);Console.WriteLine(jj);return default;}}//这里示例的是泛型类,类型TV,分别T需要有默认构造函数,V必须是值类型class indexClass2<T,V> where T:new()where V:struct{public T GetT(){return default;}public V GetV(){return default;}}struct Address{string city;string province;string zip;string[] phones;public Address(string province, string city, string zip, string[] phones){this.city = city;this.province = province;this.zip = zip;//this.phones = phones;this.phones = new string[phones.Length];//属性phones被赋值的是新的//一个数组,而不是外面传进来的数组,这样改变原来的数组也不会改变成员属性数组phones.CopyTo(this.phones, 0);}//数组属性//public string[] Phones//{// get { return phones; }//}public string[] Phones{get{string[] rtn = new string[phones.Length];phones.CopyTo(rtn, 0);return rtn;}}}
泛型的协变:
在泛型类中,子类赋值给父类变量,称为协变。
泛型的逆变: