c#从派生类继承或使用接口

时间:2014-10-01 15:02:24

标签: c# class inheritance interface

在c#中是否可以从派生类继承?例如我有以下结构,在C#中合法吗?它编译但我想知道这是否会导致问题,并在某些条件下抛出错误。

public class A   
{
    public string s1 { get; set; }
    public string s2  { get; set; }
}

public class B : A   
{
    public string s3 { get; set; }
    public string s4 { get; set; }
}

public class C : B   
{
    public C()
    {
        this.S1 = "A prop";
        this.S2 = "A prop";
        this.S3 = "B prop";
        this.S4 = "B prop";
    }

    public string s5 { get; set; }
    public string s6 { get; set; }
}

我也可以使用界面但是根据我的理解,界面只是对实现它的任何东西强制执行合同。所以我仍然需要在派生类中实现所有属性。我猜这不是代码,所以也许这是正确的方法吗?在这种情况下,我认为C实现IA和IB只意味着C必须实现属性s1,s2,s3和s4。那是对的吗?如果是这样,这是更好的方法吗?如果我在两种情况下都不在,请告诉我。感谢

interface IA   
{
    string s1 { get; set; }
    string s2  { get; set; }
}

interface  IB : IA   
{
    string s3 { get; set; }
    string s4  { get; set; }
}

public class C : IA, IB   
{
    public C()
    {
        this.S1 = "A prop";
        this.S2 = "A prop";
        this.S3 = "B prop";
        this.S4 = "B prop";
    }

    public string s1 { get; set; }
    public string s2 { get; set; }
    public string s3 { get; set; }
    public string s4 { get; set; }
    public string s5 { get; set; }
    public string s6 { get; set; }
}

3 个答案:

答案 0 :(得分:3)

它非常合法,而且非常有用。查看Button的继承树:

如果需要在类之间提供通用功能,基类通常是最好的方法。

答案 1 :(得分:1)

  

在c#中是否可以从派生类继承?

如果你仔细研究一下C#及其功能,你会发现C#是一种完全面向对象的编程语言,因此答案显而易见:

另一方面,严肃的编程语言和严肃的编译器不会让你做 ilegal 事情。如果你可以编译它,它从语法的角度来看是有效的(它可能在运行时崩溃,但是一个storng类型的编译语言不允许你在设计时派生一个类并在运行时崩溃...)。

关于接口......

接口不适合模拟继承。它们是合同,它们的用例是确保实施者需要为接口成员提供实现。此外,接口支持继承,但它是为了基于其他接口创建更广泛的合同。

答案 2 :(得分:0)

您还有另一种选择〜将A类和B类抽象化。如果您不想拥有A和B的实例,请将其设为抽象或接口。

相关问题