Is it bad practice to use Action and Func all the time instead of making corresponding delegates?

被刻印的时光 ゝ 提交于 2019-12-23 12:24:01

问题


A lot of time when creating simple events in my program that other classes can subscribe to instead of making a delegate and creating an event from the delegate I just create the event with either Action or Func to avoid having to create the delegate.

Is there any downsides to doing this?


回答1:


Not really, the only downside I can think of is that if you have a logical intention (beyond the parameters and return values expected) that you want the user to satisfy that may get lost using the generic delegates.

For example:

   public delegate void ClearAllValuesDelegate(MyClass X);

   // ...

   ClearAllValuesDelegate myDelegate;

vs:

   Action<MyClass> myDelegate;

In the former, it's clear the intention is that the action should clear all the values in the reference (though there's no way to enforce this of course). Whereas Action<> just tells you what it takes and not much else. Like I said, this is just a logical difference.

But really there's no big downside that I'm aware of. Most of the time when we use Func<> and Action<> we are simply asking the caller to give us a target that satisfies the inputs/outputs only.




回答2:


The main difference to me is the difference between:

And:

Obviously, there is at least some value in having the parameter named.




回答3:


imho it's a matter of preference, to the CLR it's the same thing



来源:https://stackoverflow.com/questions/7408744/is-it-bad-practice-to-use-action-and-func-all-the-time-instead-of-making-corresp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!