简体   繁体   English

C#继承:implements + extends

[英]C# inheritance: implements + extends

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 Interface which 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 ,但我也想使用另一个类中的方法,这些方法可以在我的类中使用。

C# doesn't support multiple inheritance . C#不支持多重继承 You can derive from one class and use interfaces for your other needs. 您可以从一个类派生并使用接口满足您的其他需求。

Syntax: 句法:

class MyClass : Foo, IFoo, IBar
{
}

interface IFoo
{
}

interface IBar
{
}

class Foo
{
}

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. 请记住,您不能从特定类级别的两个类继承,它可能只有一个类和任意数量的接口。

    class Base
    {
    }

    interface I1
    {
    }

    interface I2
    {
    }

    class Derived : Base, I1, I2
    {
    }

    static void Main(String[] args)
    {

        Derived d = new Derived();
    }

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. 您只能扩展一个基类,但可以实现许多接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM