封装一个具有一个参数并返回 TResult
参数指定的类型值的方法。
C#
1 |
<span class="hljs-keyword">public</span> <span class="hljs-keyword">delegate</span> TResult Func<<span class="hljs-keyword">in</span> T,<span class="hljs-keyword">out</span> TResult>(T arg); |
类型参数
- T
此委托封装的方法的参数类型。
- TResult
此委托封装的方法的返回值类型。
参数
- arg
此委托封装的方法的参数。
返回值
- TResult
此委托封装的方法的返回值。
- 继承
Func<T,TResult>与Action<T>都是委托,而Action是一个void类型的Func,并且有对应的参数样式。
如:Func<T1,T2,TResult> Action<T1,T2>
Func<string,string> foo=str => str.ToUpper();
等价于:
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
下面为委托方法
private static string UppercaseString(string inputString) { return inputString.ToUpper(); } }
总结
1:Action用于没有返回值的方法(参数可以根据自己情况进行传递)
2:Func恰恰相反用于有返回值的方法(同样参数根据自己情况情况)
3:记住无返回就用action,有返回就用Func
发表评论