C#实现匿名接口(或抽象类) [英] C# anonymously implement interface (or abstract class)

查看:1240
本文介绍了C#实现匿名接口(或抽象类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,可以用,你可以在飞行中实现一个匿名类扩展接口。例如:

In Java it is possible to extend an interface with an anonymous class that you can implement on the fly. Example:

Runnable myRunnable = new Runnable()
{
    @Override
    public void run() { /**/ }
}

(更多关于:的 http://www.techartifact.com/blogs/2009/08/anonymous-classes -in-java.html#ixzz1k07mVIeO

这是可能的 C#?如果没有,什么都不必依赖于子类实现了过多可行的替代品?

Is this possible in C#? If not, what are viable alternatives without having to rely on implementing a plethora of subclasses?

推荐答案

没有,你不能做在C# - 但一般的替代设计方法是使用一个委托来代替。在这个例子中,你已经给了,的Runnable 使用的ThreadStart 通常代表,您可以使用匿名方法或lambda表情:

No, you can't do that in C# - but typically the alternative design approach is to use a delegate instead. In the example you've given, Runnable is usually represented using ThreadStart, and you can use an anonymous method or lambda expression:

ThreadStart start = () =>
{
    // Do stuff here
};



或者,如果你只需要运行,用正确的签名的方法,你可以使用的方法组。转换:

Or if you just have a method to run, with the right signature, you can use a method group conversion:

ThreadStart start = MethodToRunInThread;

或者在构造函数调用:

Thread t = new Thread(MethodToRunInThread);
t.Start();

如果您的真正的需要实现一个接口,你就必须真正实现它(可能在私人嵌套类)。然而,这并没有拿出非常经常在C#中,在我的经验 - 通常C#接口是这自然需要一个真正的实施反正那种,即便在Java中

If you really need to implement an interface, you'll have to really implement it (possibly in a private nested class). However, that doesn't come up terribly often in C#, in my experience - normally C# interfaces are the kind which would naturally demand a "real" implementation anyway, even in Java.

这篇关于C#实现匿名接口(或抽象类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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