使用Action和Func,而不是使相应的代理人使用不好的做法? [英] Is it bad practice to use Action and Func all the time instead of making corresponding delegates?
问题描述
这样做有什么缺点吗?
,我唯一可以想到的缺点是,如果您有希望用户满足的逻辑意图(超出预期的参数和返回值)可能会使用泛型代理丢失。
例如:
public delegate void ClearAllValuesDelegate(MyClass X) ;
// ...
ClearAllValuesDelegate myDelegate;
vs:
code> Action< MyClass> myDelegate;
在前者中,很明显,该操作应该清除引用中的所有值虽然没有办法执行这一点)。而 Action<>
只是告诉你需要什么,而不是很多。就像我说的,这只是一个合乎逻辑的区别。
但是我确实没有什么大的缺点。大多数时候,当我们使用 Func<>
和 Action<>
时,我们只是要求呼叫者给我们只能满足输入/输出的目标。
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?
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.
这篇关于使用Action和Func,而不是使相应的代理人使用不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!