2011-03-03 49 views
0

當您撥打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>>爲這種功能?

回答

16

您正在尋找Func<T, TResult>或它的其中一個15 other過載。

+1

我有同事抱怨Func 只支持多達16個參數,因此他們不能在代碼中使用它:( – 2011-03-03 15:34:17

+1

天哪,我不能_believe_我以前從來沒有見過這樣的超載!對於現在看起來像一個愚蠢的/新手的問題,我感到抱歉。當然,謝謝你的迴應:) – jameskind 2011-03-03 15:34:58

+0

@Florian Doyon - .NET 3.5只有Func <> generic「重載「最多4個參數並返回。這通常限制了它的用處。 .NET 4.0擴展到了16;如果您將超過16個參數傳遞給任何託管方法,則應該重新考慮您的架構。 – KeithS 2011-03-03 15:38:49

2

Func<>重載用[大於零]參數Func<TParam, TReturn>Func<TParam1, TParam2, TReturn>

2

你可以用new Func<inputType1, inputType2, inputType3, outputType>()做到這一點。這可以用0到16個輸入參數。您會在the System namespace中發現不同的Func過載。

+0

不完全是0到n的輸入,但0到16應該滿足大多數需求。現在他們只需要一個泛型類型參數的'params'關鍵字,它就是0到n。 – KeithS 2011-03-03 15:50:53

+0

是的,你是對的。我認爲任何人都不需要超過16人,但我會在我的帖子中改變這一點。 – 2011-03-03 16:12:40

相關問題