【问题标题】:How to make a subclass implement an interface?如何让子类实现接口?
【发布时间】:2016-06-10 08:19:34
【问题描述】:

我创建了一个类和一个子类。我在父类中也有一个接口。如何让子类实现接口?

代码是:

class Car
{ 
    public interface ISmth
    {
        void MyMethod();
    }
}
class MyCar : Car
{ 
    //implement the interface 
}

【问题讨论】:

    标签: c# class inheritance interface subclass


    【解决方案1】:

    这就是你的代码应该如何布局。

    public interface ISmth
    {
        void MyMethod();
    }
    
    class Car
    {
    }
    
    class MyCar : Car, ISmth
    {
        public void MyMethod()
        {
        }
    }
    

    似乎没有理由将ISmth 嵌套在Car 中,但如果你有一个,你当然可以这样做。

    【讨论】:

    【解决方案2】:

    你需要这样声明 MyCar:

    class MyCar: Car, Car.ISmth {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2023-03-17
      • 1970-01-01
      • 2011-11-27
      • 2016-08-31
      • 2011-06-15
      • 1970-01-01
      相关资源
      最近更新 更多