C#继承:实现+扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14139097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:48:42  来源:igfitidea点击:

C# inheritance: implements + extends

c#oopinheritance

提问by NewProger

Is it possible to do something like that in C#:

是否可以在以下内容中做类似的事情C#

public class MyClass implements ClassA extends ClassB 
{

}

I need this because: I have two classes one of which is an Interfacewhich I will be implementing in my class, but I would like to also use methods from another class, that does some stuff that I would like to use in my class.

我需要这个是因为:我有两个类,其中一个Interface是我将在我的类中实现的类,但我也想使用另一个类的方法,它可以做一些我想在我的类中使用的东西。

采纳答案by Mir

C# doesn't support multiple inheritance. You can derive from one class and use interfaces for your other needs.

C# 不支持多重继承。您可以从一个类派生并使用接口来满足您的其他需求。

Syntax:

句法:

class MyClass : Foo, IFoo, IBar
{
}

interface IFoo
{
}

interface IBar
{
}

class Foo
{
}

回答by ryadavilli

    class Base
    {
    }

    interface I1
    {
    }

    interface I2
    {
    }

    class Derived : Base, I1, I2
    {
    }

    static void Main(String[] args)
    {

        Derived d = new Derived();
    }

回答by Marcin Buciora

Try this one:

试试这个:

using System;

public interface A
{
    void DoSmth();
}

public class B
{
    public void OpA() { }
    public void OpB() { }
}

public class ClassC : B, A
{
    public void DoSmth(){}
}

Remember, you cannot inherit from two classes at specific class level, it could be only one class and any number of interfaces.

请记住,您不能在特定的类级别从两个类继承,它可以只有一个类和任意数量的接口。

回答by Adina

It should look like this:

它应该是这样的:

public class MyClass: ClassB, InterfaceA{
}

ClassB is the base class.

ClassB 是基类

InterfaceA is an interface.

InterfaceA 是一个接口

You can only extend one base class, but you can implement many interfaces.

您只能扩展一个基类,但可以实现多个接口。