代表在C#.NET中有什么优势? [英] What are the advantages of delegates in C#.NET?

查看:71
本文介绍了代表在C#.NET中有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我我的问题的答案。

Please tell me the answer for my question.

推荐答案

一些链接可帮助您开始了解优势 -

代表及其在C#.NET事件中的角色 [ ^ ]

了解C#中的代表 [ ^ ]
Couple of links to help you start understanding the advantages -
Delegates and their role in Events in C# .NET[^]
Understanding Delegates in C#[^]


学习代表 [ ^ ]和

代表和活动的好处 [ ^ ]将为您提供帮助。
Learning Delegates[^]and
Benefits of delegates and events[^] will help you.


代表提供额外的抽象级别,因为你可以抽象出代码中表达的一些动作,并将pass作为参数传递给其他方法,就像任何其他参数一样。

这被称为一等公民 。



OOP虚拟方法和后期绑定就是这样的(而这个也是一个方法参数,隐藏on),但委托没有限制:委托实例可以接受其调用列表中的任何方法;如果该方法具有匹配的签名,则它可以是虚拟的,也可以是静态的或实例方法,属于同一类或任何其他(这是委托与虚方法之间的主要区别)。



为了显示一流公民概念的主要目的,成像你有一个复杂的数据遍历算法。您希望通过某个谓词仅选择数据成员的子集部分,并对每个谓词执行某些操作。遍历算法应该是通用的,对动作和谓词都是不可知的。方法如下:



Delegates provide additional level of abstraction, because you can abstract out some action expressed in the code and pass is as a parameter in some other method, like any other parameter.
This is called "first-class citizen".

OOP virtual methods and late binding does something like that (and this is also a method parameter, hidden on), but delegated has no limitations: delegate instances can accept any method in its invocation list; if the method has matching signature it can be virtual or not, static or instance method, of the same class or any other (which is the main difference between a delegate and a virtual method).

To show the main purpose of first-class citizen conception, imaging you have a complex data traversal algorithm. You want to select only a sub-set part of data members by some predicate and perform some action on each. The traversal algorithm should be universal, agnostic to both action and predicate. Here is how:

void TraverseData(
         MyDataContainer data,
         Func<DataElement> predicate,
         Action<DataElement> dataProcessor) {
    //...
    DateElement element = //...
    if (predicate(element))
        dataProcessor(element);
    //...
} //TraverseData







另请参阅我的其他答案:代表的额外优势是什么 [ ^ ]





高级使用代理人,请参阅我关于该主题的新文章:

动态方法调度程序 [ ^ ]



-SA


这篇关于代表在C#.NET中有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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