从C#中的两个类继承 [英] inherit from two classes in C#

查看:46
本文介绍了从C#中的两个类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C#中的多重继承

我有两个类A和B.这两个类不能互相继承.我正在创建一个名为Class C的新类.现在,我想通过继承来实现A类和B类中的方法.我知道在C#中无法进行多重继承,但是还有其他方法可以做到这一点吗?

I have two classes Class A and Class B. These two classes cannot inherit each other. I am creating new class called Class C. Now, I want to implement the methods in class A and class B by inheriting. I am aware that multiple inheritance is not possible in C# but is there any other way to do this?

推荐答案

在C#中无法进行多重继承,但是可以使用接口模拟多重继承,请参见

Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.

基本思想是为要访问的类 B 上的成员(称为 IB )定义一个接口,然后使 C A 继承并通过内部存储 B 的实例来实现 IB ,例如:

The basic idea is to define an interface for the members on class B that you wish to access (call it IB), and then have C inherit from A and implement IB by internally storing an instance of B, for example:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

该页面上还说明了其他两种交替模式.

There are also a couple of other alternaitve patterns explained on that page.

这篇关于从C#中的两个类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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