如何使用接口克服多重继承在C#中的问题? [英] How does using interfaces overcome the problem of multiple inheritance in C#?

查看:159
本文介绍了如何使用接口克服多重继承在C#中的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,C#不支持多重继承,并且该解决方案是使用的接口来代替。但我不明白的是,为什么界面不会产生钻石的问题相同的方式,多重继承。如何使用接口避免多重继承的陷阱?

I understand that C# does not support multiple inheritance, and that the solution is to use interfaces instead. But what I don't understand is why interfaces doesn't create the diamond problem the same way as multiple inheritance would. How does using interfaces avoid the pitfalls of multiple inheritance?

推荐答案

一类可能的实施的任意数量的接口,即使这些接口扩展其他接口也是如此。多重的继承的是不可能只的

One class may implement any number of interfaces, even if those interfaces extend other interfaces as well. Multiple inheritance is not possible only with classes.

// This is not allowed
class A { void A() {} }
class B { void B() {} }
class C : A, B {}

// This is allowed
interface IA { void A(); }
interface IB { void B(); }

class A : IA, IB
{
    public void A() {}
    public void B() {}
}

钻石问题类的存在是因为有冲突实现的可能性(如 A B 有同样的方法和 C 同时扩展,这方法没有考虑?)。接口,另一方面,只要求一个执行类型为具有他们宣称的方法。

The diamond problem exists with classes because there is a possibility of clashing implementations (if A and B have the same method and C extends both, which method does it take?). Interfaces, on the other hand, simply require an implementing type to have the methods that they declare.

如果完全相同的方法是在两个接口定义,并且一个类实现这两个接口,这并不重要。所有类需要做的是提供用于该方法的实施,使code可以被写入调用该方法。这意味着,这个作品:

If the exact same method is defined in two interfaces, and a class implements both interfaces, that doesn't matter. All the class needs to do is provide an implementation for the method so that code can be written to call that method. Meaning, this works:

interface IA { void Method(int x); }
interface IB { void Method(int x); }

class A : IA, IB
{
    public void Method(int x)
    {
        Console.WriteLine(x);
    }
}

请注意,一个类可能仍然另一个类继承,以及任意数量的接口:

Note that a class may still inherit from one other class, plus any number of interfaces:

class A : B, IA, IB {}

这篇关于如何使用接口克服多重继承在C#中的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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