Action<>和Func<>区别

 

Action<>和Func<>其实都是委托的【代理】简写形式。

简单的委托写法:

 1 //普通的委托
 2 public delegate void myDelegate(string str);
 3 
 4 //Delegate委托调。
 5 myDelegate dDelegate = new myDelegate(SayHellow);
 6 dDelegate("Mr wang");
 7 
 8 //测试方法
 9 public static void SayHellow(string name)
10 {
11      Console.WriteLine("Hello,"+name);
12      Console.ReadLine();
13 }
View Code

Action<>指定那些只能输入参数,没有返回值的委托。

 1 Action<string> action = SayHellow; //Action<string>中string为参数类型。
 2 action("ZhangSan");
 3 
 4 
 5 //测试方法
 6 public static void SayHellow(string name)
 7 {
 8             Console.WriteLine("Hello,"+name);
 9             Console.ReadLine();
10  }
View Code


Func<>使用方法和Action<>相似,区别是这个 有返回值。

1 Func<string,string> func=SayHello; //Func<>中参数前面都是方法所传参数类型,只有最后一个类型为委托返回 类型。
2 Console.WriteLine(func("ZhangSan"));
3 
4 
5 //测试方法。
6 public static string SayHello(string name)
7 {
8        return "Hello." + name;
9  }
View Code

 

posted @ 2015-04-30 14:49  及乌及国  阅读(687)  评论(2编辑  收藏  举报