當您撥打Action<T>
時,您將傳入一個類型爲T的變量,該變量可供委託中定義的代碼使用,例如,是否有代表結合了Func <T>和Action <T>的功能?
var myAction = new Action<string>(param =>
{
Console.WriteLine("This is my param: '{0}'.", param);
});
myAction("Foo");
// Outputs: This is my param: 'Foo'.
當你調用一個Func<T>
委託將返回一個類型的T A變量,例如
var myFunc = new Func<string>(() =>
{
return "Bar";
});
Console.WriteLine("This was returned from myFunc: '{0}'.", myFunc());
// Outputs: This was returned from myFunc: 'Bar'.
這裏的問題 -
是否有這將需要輸入參數和也返回一個值的第三委託類型?喜歡的東西 -
var fooDeletegate = new FooDelegate<string, int>(theInputInt =>
{
return "The Answer to the Ultimate Question of Life, the Universe, and Everything is " + theInputInt;
});
Console.WriteLine(fooDeletegate(42));
// Outputs: The Answer to the Ultimate Question of Life, the Universe, and Everything is 42
如果這樣的事情不存在,將有可能使用Action<Func<sting>>
爲這種功能?
我有同事抱怨Func只支持多達16個參數,因此他們不能在代碼中使用它:( –
2011-03-03 15:34:17
天哪,我不能_believe_我以前從來沒有見過這樣的超載!對於現在看起來像一個愚蠢的/新手的問題,我感到抱歉。當然,謝謝你的迴應:) – jameskind 2011-03-03 15:34:58
@Florian Doyon - .NET 3.5只有Func <> generic「重載「最多4個參數並返回。這通常限制了它的用處。 .NET 4.0擴展到了16;如果您將超過16個參數傳遞給任何託管方法,則應該重新考慮您的架構。 – KeithS 2011-03-03 15:38:49