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

查看:20
本文介绍了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() {}
}

类存在菱形问题,因为有可能实现冲突(如果 AB 具有相同的方法并且 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.

如果在两个接口中定义了完全相同的方法,并且一个类实现了两个接口,那没关系.该类需要做的就是为该方法提供一个实现,以便可以编写代码来调用该方法.意思是,这有效:

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天全站免登陆