C#中的Action<>和Func<>

简介:

其实他们两个都是委托【代理】的简写形式。
一、【action<>】指定那些只有输入参数,没有返回值的委托
Delegate的代码:
[csharp] view plain copy
public delegate void myDelegate(string str); 
public static void HellowChinese(string strChinese) 

Console.WriteLine("Good morning," + strChinese); 
Console.ReadLine(); 
}

myDelegate d = new myDelegate(HellowChinese); 
d("Mr wang");

用了Action之后呢:

[csharp] view plain copy
public static void HellowChinese(string strChinese) 

Console.WriteLine("Good morning," + strChinese); 
Console.ReadLine(); 
}

Action<string> action = HellowChinese; 
action("Spring."); 
就是相当于省去了定义委托的步骤了。

二、func<> 这个和上面的那个是一样的,区别是这个有返回值!
[csharp] view plain copy
public static string HelloEnglish(string strEnglish) 

return "Hello." + strEnglish; 
}

Func<string, string> f = HelloEnglish; 
Console.WriteLine(f("Srping ji")); 
Console.ReadLine();


本文转自 宁金峰 51CTO博客,原文链接:http://blog.51cto.com/13243523/2045126,如需转载请自行联系原作者

相关文章
|
10月前
|
Dart
Dart报The return type ‘bool‘ isn‘t a ‘void‘, as required by the closure‘s context
Dart报The return type ‘bool‘ isn‘t a ‘void‘, as required by the closure‘s context
|
C++
一个函数两个return
一个函数两个return
146 0