c# - 从继承接口(interface)显式设置内部属性 C#

标签 c# inheritance interface

我有一个场景。我正在尝试包装我的代码,以便我拥有通用实体,这些实体可以根据它们所在的领域实例化自己。

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

简而言之,我在接口(interface)(IFoo)内有一个接口(interface)(IBar)类型的属性,该属性继承另一个接口(interface)(IFooBase),并且在该基接口(interface)内有另一个属性,该属性与接口(interface)中的属性同名上面的类型是其原始(IBarBase)的基接口(interface)

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

任何关于如何使用 Bar 的实例化对象分配 IBarBase 的建议将不胜感激(该对象实际上是 IBar 的实现并从 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;}
}

最佳答案

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

public new IBar inst { get; set; }

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

您可以显式实现接口(interface)成员:

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; } }
}

关于c# - 从继承接口(interface)显式设置内部属性 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36059985/

相关文章:

c# - 在 C# 中创建的数字签名在 C++ 中不验证

java - Android开发中如何管理Activity继承

c++ - 友元函数中指向基类参数类型的指针

oop - 如何在 Go 中实现一个抽象类?

java - ClassOne 中的 doSomething() 无法实现 InterfaceOne 中的 doSomething(),尝试分配较弱的访问权限,已公开

c# - 找不到类型或命名空间名称 'Skeleton'

c# - 将 html 组件添加到页面的 AJAX 最佳实践

c# - 如何暂停创建新线程直到旧线程结束

.net - 关于.NET 中接口(interface)继承的问题

java - 如何实现类列表中不常见的方法/接口(interface)?