从继承的接口C#

时间:2016-03-17 12:00:47

标签: c# inheritance interface

我有一个场景。我试图将我的代码包装起来,以便我拥有根据它们所在领域实例化的通用实体。

就像洋葱一样,它只有一层它自己处理,但同时允许更高层次的人触发内层开始做某事。它允许我以更好,更可重用的方式打包我的组件,因为我将能够实现安全传播到所有必需模块的代码,而不会影响可能来自相同基类的更高级别。所以基本上会有一个级别的层次结构,类将共享共性。

简而言之,我在接口(IFoo)中有一个类型为interface(IBar)的属性,它继承了另一个接口(IFooBase),我在这个基接口中有另一个属性,它与接口的属性名称相同以上类型是其原始的基础界面(IBarBase)

我的问题是我的Foo实现,它调用来自FooBase的方法,访问IBar的属性无法访问IBarBase,因为该对象未实例化,原因是同时继承的接口执行属性隐藏而不是覆盖。

我将非常感谢有关如何将实例化的Bar(其中实际上是IBar的实现并从IBarBase派生)分配给IBarBase,以便我可以从较低的位置访问该属性。级别执行某项任务。

抱歉这听起来太复杂了?我不确定我是否有任何意义,之前的代码仅供参考。还有一张图片用于说明

enter image description here

public interface IFoo : IFooBase
{
    new IBar inst { get; set; }
}

public interface IFooBase
{
    IBarBase inst { get; set; }
    void SetEventHandlers();
}

public interface IBar : IBarBase
{
    int stuff { get; set; }
}

public interface IBarBase
{
    int otherStuff { get; set;}
}

public class Foo : FooBase, IFoo
{
    public Foo()
    {
        inst = new Bar();
        SetEventHandler();
    }

    public new IBar inst { get; set; }
}

public class FooBase : IFooBase
{
    public void SetEventHandler()
    {
        inst.otherStuff = 123;
    }

    public IBarBase inst { get; set; }
}

public class Bar : BarBase, IBar
{
    public int stuff { get; set; }
}

public class BarBase : 
{
    public int otherStuff { get; set;}
}

2 个答案:

答案 0 :(得分:4)

您在inst中创建了另一个变量Foo(请注意new关键字):

public new IBar inst { get; set; }

它会隐藏您基类中的其他inst。因此,您未在FooBase.inst中设置Foo,而是设置Foo.inst。因此,FooBase.inst为空。

您可以明确地实现接口成员:

public class Foo : FooBase, IFoo
{
    IBar IFoo.inst { get { return instAsIBar; } set { instAsIBar = value; } }

    public IBar instAsIBar { get { return (IBar)this.inst; } set { this.inst = value; } }
}

答案 1 :(得分:1)

您应该使用an explicit implementation of the interface而不是覆盖inst属性:

public class Foo : FooBase, IFoo
{
   public Foo() 
   {
        inst = new Bar();
        SetEventHandlers();
   }

   IBar IFoo.inst { get; set; }
}

然后这个测试通过:

[TestFixture]
public class TC 
{
    [Test]
    public void t() 
    {
        Foo f = new Foo();
        ((FooBase)f).inst.otherStuff.Should().Be(123);
    }
}
相关问题