C#泛型委托及约束

泛型委托:

 1 namespace 泛型委托
 2 {
 3     public delegate void Mydelegate<T>(T msg);
 4     class Program
 5     {
 6 
 7         static void Main(string[] args)
 8         {
 9             //Mydelegate<int> myDelgate = M1;
10             //M1(5);
11             Mydelegate<string> mydelgate = M4;
12             M4("abcd");
13             Console.ReadKey();
14 
15         }
16         #region 泛型委托
17         public static void M1(int msg)
18         {
19             Console.WriteLine(msg);
20         }
21         public static void M2(double msg)
22         {
23             Console.WriteLine(msg);
24         }
25         public static void M3(float msg)
26         {
27             Console.WriteLine(msg);
28         }
29         public static void M4(string msg)
30         {
31             Console.WriteLine(msg);
32         }
33         public static void M5(Person msg)
34         {
35             Console.WriteLine(msg);
36         }
37         #endregion
38     }
39     class Person { };
40 
41 }
View Code
 1     class Program
 2     {
 3 
 4         static void Main(string[] args)
 5         {
 6 
 7             List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
 8             List<int> listresult = list.FindAll(n => n > 4);
 9             for (int i = 0; i < listresult.Count; i++)
10             {
11                 Console.WriteLine(listresult[i]);
12             }
13             Console.ReadKey();
14         }
15 
16     }

系统内置的泛型委托

 1     class Program
 2     {
 3 
 4         static void Main(string[] args)
 5         {
 6 
 7             #region 系统内置的泛型委托
 8             //action委托无返回值
 9             Action<int, int> md = (int n1, int n2) => { Console.WriteLine(n1 + n2); };
10             md(3,4);
11             Console.ReadKey();
12 
13             //当需要存储带返回值的方法的时候,就需要使用另外一个泛型委托Func
14             Func<string> md1 = () => System.DateTime.Now.ToShortDateString();
15             Console.WriteLine(md1());
16             Console.ReadKey();
17             #endregion
18        
19         }
20 
21     }
View Code

泛型约束

 1     #region 泛型约束
 2     //表示使用泛型约束,约束了T只能是值类型
 3     class MyClass<T> where T : struct
 4     {
 5 
 6     }
 7     //表示引用类型使用泛型约束,约束了T只能是引用类型
 8     class MyClass2<T> where T : class
 9     {
10 
11     }
12     //限制了T必须是实现了某个接口的类型,要求T必须是实现了IComparable接口的类型或者是子类型
13     class MyClass3<T> where T : IComparable
14     {
15 
16     }
17     //要求T必须是Person类型,或者是Person类的子类型
18     class MyClass4<T> where T : Person
19     {
20 
21     }
22     //要求T必须是Person类型,或者是Person类的子类型,而且T必须具有一个无参的构造函数
23     class MyClass5<T>
24         where T : Person
25         where T : new()
26     {
27 
28     }
29     //要求V必须是T类型或者T的子类型
30     class MyClass6<T, V> where V : T
31     {
32 
33     }
34 
35     class Person { };
36     #endregion
View Code

 

posted @ 2015-12-17 12:59  菜鸟,你好  阅读(533)  评论(0编辑  收藏  举报