定义如下:
Func<(Of <(T, TResult>)>)
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
public delegate TResult Func<T, TResult>(
T arg
)
【类型参数 T 此委托封装的方法的参数类型。 TResult 此委托封装的方法的返回值类型。
参数
arg 类型:T此委托封装的方法的参数。
返回值
类型:TResult 封装的方法的返回值。可以使用此委托表示一种能以参数形式传递的方法,而不用显式声明自定义委托。该方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有一个通过值传递给它的参数,并且必须返回值。】
Demo1:
C# 复制代码
using System;
delegate string ConvertMethod(string inString);
public class DelegateExample
{
public static void Main()
{
// Instantiate delegate to reference UppercaseString method
ConvertMethod convertMeth = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMeth(name));
} private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
下面是采用func来简写的上面的代码:
using System;
public class GenericFunc
{
public static void Main() { // 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();
}
}
亦可:
using System;
public class Anonymous
{
public static void Main()
{
Func<string, string> convert = delegate(string s)
{ return s.ToUpper();};
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
亦可
using System;
public class LambdaExpression
{
public static void Main() { Func<string, string> convert = s => s.ToUpper();
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
最后一个DEMO:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
static class Func
{
static void Main(string[] args)
{
// Declare a Func variable and assign a lambda expression to the
// variable. The method takes a string and converts it to uppercase.
Func<string, string> selector = str => str.ToUpper();
// Create an array of strings.
string[] words = { "orange", "apple", "Article", "elephant" };
// Query the array and select strings according to the selector method.
IEnumerable<String> aWords = words.Select(selector);
// Output the results to the console.
foreach (String word in aWords)
Console.WriteLine(word);
}
}