我正在尝试创建一个使用相同属性但始终具有其他派生类型的接口(interface)继承系统。因此,基础属性应以某种方式被派生接口(interface)覆盖或隐藏。

例如,有两个接口(interface),分别衍生为丈夫和妻子的男人和女人。男人和丈夫的界面都具有“甜心”属性,而女人和妻子的界面均具有“亲爱的”属性。现在,男人的“甜心”属性是“女人”类型,而丈夫的“甜心”属性应该是“妻子”(源于“女人”)。和女人和妻子的“亲爱的”属性(property)一样。

public interface Man // base interface for Husband
{
    Woman sweetheart { get; set; }
}

public interface Woman // base interface for Wife
{
    Man darling { get; set; }
}

public interface Husband : Man // extending Man interface
{
    new Wife sweetheart { get; set; } // narrowing "sweetheart" property's type
}

public interface Wife : Woman // extending Woman interface
{
    new Husband darling { get; set; } // narrowing "darling" property's type
}

public class RandomHusband : Husband // implementing the Husband interface
{
    private RandomWife wife;
    public Wife sweetheart { get { return wife; } set { wife = value; } }
}

public class RandomWife : Wife // implementing the Wife interface
{
    private RandomHusband husband;
    public Husband darling { get { return husband; } set { husband = value; } }
}

此代码是错误的,它不起作用。我收到通知,因为我没有实现基本的Man.sweetheartWoman.darling属性,并且实现的Husband.sweetheartWife.darling不会实现,因为类型不匹配。有什么方法可以将属性的类型缩小到派生的类型?您如何用C#实现它?

最佳答案

您仍然需要满足男女界面以及丈夫和妻子的要求。

public class RandomWife : Wife // implementing the Wife interface

    {
        private RandomHusband husband;
        public Husband darling { get { return husband; } set { husband = value; } }
        public Man  Wife.darling { get { return husband; } set { /* can't set anything */ } }

    }

关于c# - 派生的C#接口(interface)属性可以覆盖具有相同名称的基本接口(interface)属性吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13519167/

10-12 07:36
查看更多