使用Action和Func,而不是使相应的代理人使用不好的做法? [英] Is it bad practice to use Action and Func all the time instead of making corresponding delegates?

查看:135
本文介绍了使用Action和Func,而不是使相应的代理人使用不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中创建简单事件的时候,很多时候,其他类可以订阅而不是委托,并从代理创建一个事件,我只需用Action或Func创建事件,以避免创建委托。



这样做有什么缺点吗?

解决方案

,我唯一可以想到的缺点是,如果您有希望用户满足的逻辑意图(超出预期的参数和返回值)可能会使用泛型代理丢失。



例如:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆