开发者

Is Func<T, TResult> a special delegate or can we create it manually also?

Func<T, TResult> delegate is for a delegate with a single param and return type of TResult.

Is this a special delegate or is it something 开发者_如何学编程we can code ourselves manually?

e.g. could I create a Func<T, TResult> but that accepts 2 input params?


"Func" is actually a family of classes in the System namespace, namely:

Func<TResult> (0 params), Func<T,TResult> (1 param), Func<T1,T2,TResult> (2 params) ... Func(17) (16 params).

There are 17 different "Func" classes total, supporting from 0 to 16 parameters. It is allowable for them to share the name in code ("Func") even though they are actually different types (Func, Func', Func'', etc) thanks to how Generics work in .NET -- the number of generics determines/disambiguate which actual type is used.

Happy coding.


As far as converting between delegates, this may be of use (runs in LINQPad, "C# Program"):

delegate int MyDelegate (int y);

void Main()
{
    Func<int,int> fun1 = (q) => q * q;
    MyDelegate del = new MyDelegate(fun1); // Convert the "Func" delegate to custom...
    Func<int,int> fun2 = new Func<int,int>(del); // ...and back
}


There's already a Func<TParam1, TParam2, TResult> that does this. But what you're asking for is a little different (you know that both parameters are the same type). You can still use the same type parameter twice with the built-in Func, but if you really want to you could do this:

public delegate TResult MyFunc<T, TResult>(T param1, T param2);


There's already a Func<T1, T2, TResult> that accepts two input parameters.

To answer your question though, no, it's not special compared to any other delegate, and you could create your own, but why would you?


You shouldnt have to create your own Func. There are overloads for Func that go up to 16 args.

http://msdn.microsoft.com/en-us/library/dd402862.aspx

and every variation in between. Essentially, the first n-1 args are input and the last is the return value.

So, Func<int,int,int,int> compares to a delegate that takes 3 int args and returns int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜