【问题标题】:If I have two interfaces, can one class inherit both?如果我有两个接口,一个类可以继承两者吗?
【发布时间】:2013-12-11 02:56:49
【问题描述】:

我有一个有 2 个接口的类,我有一些带有子类的超类,我希望超类继承这两个接口。如果我只是引用它所在的接口类,它会起作用吗?即 SuperClass : Myinterfaces

这是带有接口的类

public class Myinterfaces
{
    public interface IBakeable
    {
        int OvenTemp { get; }
    }

    public interface IAccounting
    {
       int Cost { get; }
    }

    public enum Colors
    { 
        red = 1,
        blue,
        yellow
    }
}

这是一个超类的例子

public class CeramicsSuperClass : Myinterfaces
{
    public string ItemName { get; set; }
    public int Cost { get; set; }
    public int OvenTemp { get; set; }
}
public class Vases : CeramicsSuperClass
{
    private int _BaseDiam;
    public Vases(int diam)
    {
        _BaseDiam = diam;
    }

}

【问题讨论】:

  • 是的,它确实有效,而且您似乎还没有亲自尝试过?
  • @KingKing 我遇到了问题。在主程序中,我试图添加到 IBakeable 和 IAccounting 类型的列表中,但它们不会接受来自超类或子类的任何实例化实例 9
  • 它不起作用,因为您的课程以错误的方式实现了多接口,请参阅我的答案了解详细信息。

标签: c# inheritance interface subclass superclass


【解决方案1】:

简单的答案: 您可以继承多个接口,而不是多个类。

public interface InterfaceA 
{
    string PropertyA {get;}
}

public interface InterfaceB
{
    string PropertyB {get;}
}

public abstract class BaseClassForOthers : InterfaceA, InterfaceB
{
    private string PropertyA {get; private set;}
    private string PropertyA {get; private set;}

    public BaseClassForOthers (string a, string b)
    {
        PropertyA  = a;
        PropertyB  = b;
    }

}

public class SubClass : BaseClassForOthers 
{
    public SubClass (string a, string b)
        : base(a, b)
    {
    }

}

可能看这里会让你大致了解(关于接口使用的 msdn 链接): http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx

【讨论】:

    【解决方案2】:

    你在为一个类实现多接口时做错了,试试这个吧:

    public class CeramicsSuperClass : IBakeable, IAccounting {
      public string ItemName { get; set; }
      public int Cost { get; set; }
      public int OvenTemp { get; set; }
    }
    

    一个类只能从另一个类继承,但它可以实现尽可能多的接口。当一个类从另一个类继承并实现某个接口时,应该首先列出基类,然后接口是这样的:

    //class A inherits from class B and implements 2 interfaces IC and ID
    public class A : B, IC, ID {
      //...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2011-06-03
      • 1970-01-01
      • 2019-08-04
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多