如果我有两个接口,一个类可以继承吗?

时间:2013-11-26 05:16:03

标签: c# inheritance interface subclass superclass

我有一个带有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;
    }

}

2 个答案:

答案 0 :(得分:4)

您正在以错误的方式为类实现多接口,请尝试以下方法:

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 {
  //...
}

答案 1 :(得分:2)

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

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

相关问题