使用委托类型与方法
我发现系统命名空间中提供的委托类型的使用越来越多(Action
;Predicate
等)。由于这些是委托,我的理解是它们应该用在我们过去传统上使用委托的地方(异步调用、启动线程、事件处理等)。在下面的场景中使用这些委托类型只是偏好还是被认为是实践;而不是使用对我们已声明的方法(或匿名方法)的调用:
public void MyMethod()
{
Action<string> action = delegate(string userName
{
try
{
XmlDocument profile = DataHelper.GetProfile(userName);
UpdateMember(profile);
}
catch (Exception exception)
{
if (_log.IsErrorEnabled) _log.ErrorFormat(exception.Message);
throw (exception);
}
};
GetUsers().ForEach(action);
}
起初,我发现代码比使用声明或匿名方法不太直观。我开始以这种方式编码,并想知道这方面的观点是什么。上面的例子都在一个方法中。这个代表是否过度使用?
I see increasing use of the delegate types offered in the System namespace (Action<T>
; Predicate<T>
etc). As these are delegates, my understanding is that they should be used where we have traditionally used delegates in the past (asynchronous calls; starting threads, event handling etc). Is it just preference or is it considered practice to use these delegate types in scenarios such as the below; rather than using calls to methods we have declared (or anonymous methods):
public void MyMethod()
{
Action<string> action = delegate(string userName
{
try
{
XmlDocument profile = DataHelper.GetProfile(userName);
UpdateMember(profile);
}
catch (Exception exception)
{
if (_log.IsErrorEnabled) _log.ErrorFormat(exception.Message);
throw (exception);
}
};
GetUsers().ForEach(action);
}
At first, I found the code less intuitive to follow than using declared or anonymous methods. I am starting to code this way, and wonder what the view are in this regard. The example above is all within a method. Is this delegate overuse?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于简单的
foreach
循环,我更喜欢普通的语言构造 - 请参阅 此博文代表 Eric Lippert 的观点。我认为这里使用代表有点无端。在其他情况下——尤其是使用 LINQ——它很有意义。
委托是一种允许专业化的好方法,无需声明和实现接口或从类型派生以覆盖方法的开销......但当然,一切都要适度。如果您要实现多种方法(并且您确实想为所有方法指定行为),那么接口就更有意义。如果您确实要创建一个专门的类型,那么派生和重写就有意义了。然而,如果您想要一种策略模式,那么委托的工作方式非常巧妙。
For a simple
foreach
loop, I would prefer the normal language construct - see this blog post for Eric Lippert's view. I think the use of a delegate here is somewhat gratuitous.In other cases - particularly with LINQ - it makes a lot of sense.
Delegates are a nice way of allowing specialization without the overhead of declaring and implementing an interface or deriving from a type in order to override methods... but everything in moderation, of course. If you've got several methods to implement (and you really want to specify behaviour for all of them) then an interface makes more sense. If you're genuinely creating a specialized type then deriving and overriding make sense. If you're wanting a strategy pattern, however, then delegates work very neatly.