我有一些代碼(不是我創作的),我不明白:這是什麼代碼:Func鍵< T, string >,我不明白
private Func<ControllerContext, string> ThemeSelector { get; set; }
所以這不是一個型,這是Func < T,字符串>,我不知道這種事情是如何命名的,但我無法在Google上找到一些解釋。有人可以給我一些解釋給我一個鏈接來解釋嗎?
謝謝。
我有一些代碼(不是我創作的),我不明白:這是什麼代碼:Func鍵< T, string >,我不明白
private Func<ControllerContext, string> ThemeSelector { get; set; }
所以這不是一個型,這是Func < T,字符串>,我不知道這種事情是如何命名的,但我無法在Google上找到一些解釋。有人可以給我一些解釋給我一個鏈接來解釋嗎?
謝謝。
Func<ControllerContext, string>
是特定類型的通用Func<T,K>
。 在完全理解之前,您需要先了解泛型。
因此ThemeSelector只是該類型的屬性,它具有setter和getter。
的函數功能類型是委託類型,其表示一個函數,它類型T的一個參數,並返回類型的實例K.
這意味着,可以分配任何這樣的功能的特性。例如:
private string MyFunction(ControllerContext context) {
return "Hello world!";
}
...
ThemeSelector = MyFunction;
Console.WriteLine(ThemeSelector(null));
將打印「Hello world!」在控制檯。
這是一個委託類型,即這是一個屬性,它可以被設置。它可以被稱爲方法。
例如
/* 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();
}
這是一種類型!其實它是一個代表類型。它表示一種可以在不明確聲明委託的情況下使用的方法。
該類型是一種通用類型。在你的例子中的類型是Func<T, TResult>
,它表示一個方法,它有一個T型參數並返回一個TResult類型的值。具體到你的榜樣,它代表的是有一個ControllerContext
參數的方法,並返回一個string
值:
string ThemeSelectorHandler(ControllerContext context) {
returns context.ToString();
}
延伸閱讀:
你有沒有檢查MSDN或ASP.net? – 2012-02-04 08:33:17
這可能是這樣的重複:http://stackoverflow.com/questions/7901609/theme-selector-idea-for-a-blog-engine-written-with-asp-net-mvc – 2012-02-04 08:35:54
@ Floradu88:我嘗試自己找,但我不知道它是如何命名的,所以很難搜索......在msdn上,我不清楚它。 – Bronzato 2012-02-04 08:36:17