开发者

use Func<> (or Action<>) or create own delegate?

Which one is better in, say, parameter type in a method (not related to LINQ). Apparently Func is better since it's simpler, more descriptive, and if everyone is using this everything will become compatible (good). However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?

Edits:

  • Apparently Func<> was only available in 3.5, so this can possible be the main reason that I saw non-Func delegates. Any other reason to not use Func? (example: this is from .NET4)

  • The same question also applies for Action开发者_StackOverflow<>


Func<> is useful when it's very clear what they're used for, and the number of inputs is small.

When the number of inputs is larger, or there could be some ambiguity over the intent - then using a delegate with named arguments makes things clearer.


They are for all purposes the same, except when the method has an Expression parameter. Those need to be defined as a 'lambda' and not delegate. This would be very problematic when dealing with IQueryable and getting the IEnumerable invoked/resolved instead (eg LINQ2SQL).


Func<> and Action<> are preferable if they are actually appropriate in your case. Runtime creates instances of every type used in your program, and if you use Func once it means that the instance of type was created. In case of custom delegate things go in different way and new types will be created even though they are essentially similar to existing.

However sometimes custom delegates make code clearer.


However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?

Some of this is historic: APIs defined before C#3/.NET3 when Action<> and Func<> were added. For events EventHandler<T> is a better choice for events because it enforces the right convention.


You can always create a class which holds the n number of input as class properties and pass the object of the class a single input in the func<> delegate

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜