派生类可以选择从基类中实现多少属性来实现吗?

时间:2016-05-21 08:01:10

标签: c# class inheritance interface

我有一个课程让我们说3个属性。我希望这个类是通过接口派生的,每当接口继承时,我希望能够保留一些未使用的属性,我不希望它们出现在IntelliSense中。从接口派生的每个类都可以实现不同数量的属性。我还有一个普通的类,它直接从基类继承并实现所有3个属性。

有可能这样做吗?

这是我对自己如何想象的说明,希望它会让你更清楚。

enter image description here

2 个答案:

答案 0 :(得分:1)

您无法从类派生接口,但您可以从接口实现类。

因此,从具有较小属性集的接口开始,然后在子类中实现它,并为其添加其他属性。

答案 1 :(得分:0)

这就是你要找的东西吗?

public class BaseClass : ISomeInterface, ISomeOther
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
    public int Prop3 { get; set; }
}

public class Derived : BaseClass
{
    // inherits all 3 props
}

public interface ISomeInterface
{
    int Prop1 { get; }
    int Prop2 { get; }
}

public interface ISomeOther
{
    int Prop3 { get; }
}

public static class Program
{
    public static void Main()
    {
        BaseClass instance1 = new BaseClass();      // IntelliSense shows all 3 props
        Derived instance2 = new Derived();          // IntelliSense shows all 3 props
        ISomeInterface instance3 = new BaseClass(); // IntelliSense shows 2 props from interface
        ISomeOther instance4 = new BaseClass();     // IntelliSense shows only Prop3
    }
}

通过分解某些界面中的功能,您可以根据所使用的界面提供某个功能子集。

相关问题