假设我们有:
interface Foo { bool Func(int x); } class Bar: Foo { bool Func(int x) { return (x>0); } } class Baz: Foo { bool Func(int x) { return (x<0); } }现在,我们能折腾周围酒吧和巴兹作为FOOS ,并调用它们的函数功能的方法。
Now we can toss around Bar and Baz as a Foos and call their Func methods.
代表这简化了一点:
delegate bool Foo(int x); bool Bar(int x) { return (x<0); } bool Baz(int x) { return (x>0); }现在,我们可以围绕酒吧和巴兹折腾如美孚代表。
Now we can toss around Bar and Baz as Foo delegates.
什么是代表的真正的好处,除了越来越短代码?
What is the real benefit of delegates, except for getting shorter code?
推荐答案有一个细微的差别,代表们可以访问类的成员变量中,它们被定义。在C#(Java不同)所有内部类都认为是静态的。因此,如果您使用的界面来管理回调,例如,一个按钮一个ActionListener。实施内部类需要传递(通过构造),以包含类的,它可能需要回调过程中与交互的部分引用。代表们没有因此这种限制减少了代码来实现回调所需的时间。
There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed (via the constructor) references to the parts of the containing class that it may need to interact with during the callback. Delegates do not have this restriction therefore reduces the amount of code required to implement the callback.
更短,更简洁的代码也是值得的好处。
Shorter, more concise code is also a worthy benefit.
更多推荐
有代表不只是速记接口?
发布评论