这段代码是什么:Func< T,string>我不明白

时间:2012-02-04 08:31:14

标签: c# asp.net delegates

我有一些我不理解的代码(不是我写的):

private Func<ControllerContext, string> ThemeSelector { get; set; }

所以这不是类型,这是 Func&lt; T,字符串&gt; ,我不知道这种事情是如何命名的,但我无法在Google上找到一些解释。有人可以给我一些解释,给我一个解释链接吗?

感谢。

4 个答案:

答案 0 :(得分:3)

这是一个委托类型,即这是一个属性,可以设置。它可以称为方法。

例如

/* Action<String> is a delegate, get it as an object*/
public void Foo (String[] arr, Action<String> instruction) {
    foreach (var element in arr) {
        //use it as a method
        instruction(element);
    }
}

修改

同样适用于Func

// Func<Int32, Boolean> means that this is a function which accepts one argument as an integer and returns boolean.
public void Foo(Int32 data, Int32 otherData, Func<Int32, Boolean> instruction) {
    var result1 = instruction(data);
    var result2 = instruction(data2);
    Console.WriteLine(result1==result2);
}

修改

更全面的例子。

//This methods accepts the third parameter as a function with 2 input arguments of type
// Int32 and return type String
public static void DoSomething(Int32 data1, Int32 data2, Func<Int32, Int32, String> whatToDo) {
    var result = whatToDo(data1, data2);
    Console.WriteLine(result);
}

public static Main(String[] args) {
    // here we are calling the DoSomething and
    // passing the Concat method as if it was an object.
    DoSomething(1, 2, Concat);
    // The same with multiply concat.
    DoSomething(7, 2, MultiplyConcat);
}
public static String Concat(Int32 arg1, Int32 arg2) {
    return arg1.ToString() + " " + arg2.ToString():
}
public static String MultiplyConcat(Int32 arg1, Int32 arg2) {
    return (arg1 * arg2).ToString();
}

答案 1 :(得分:3)

Func<ControllerContext, string>是通用Func<T,K>的特定类型。 在完全理解之前,您需要首先了解泛型。

因此,ThemeSelector只是该类型的属性,具有setter和getter。

Func类型是一个委托类型,它表示一个函数,它接受一个类型为T的参数并返回一个类型为K的实例。

这意味着您可以将任何此类功能分配给该属性。 E.g:

private string MyFunction(ControllerContext context) {
    return "Hello world!";
}

...

ThemeSelector = MyFunction;

Console.WriteLine(ThemeSelector(null));

将打印“Hello world!”在控制台中。

答案 2 :(得分:1)

这是一种类型!实际上它是委托类型。它表示可以在不明确声明委托的情况下使用的方法。

类型是泛型类型。示例中的类型为Func<T, TResult>,表示具有一个类型为T的参数并返回TResult类型的值的方法。具体到您的示例,它表示具有ControllerContext参数并返回string值的方法:

string ThemeSelectorHandler(ControllerContext context) {
    returns context.ToString();
}

进一步阅读:

答案 3 :(得分:0)

*委托是指向函数的指针。
* Func是内置委托类型。尖括号中的最后一个类型是结果类型。
*继承:对象->委托->函数
* Action是指向没有返回值的函数的内置委托。

相关问题