C# 扩展用作属性的嵌套类

C# 扩展用作属性的嵌套类,c#,inheritance,interface,properties,nested-class,C#,Inheritance,Interface,Properties,Nested Class,我编写了一个嵌套类,用作属性包。这个类被用作我命名为Properties的属性。我想通过接口扩展属性的数量 我写了这个例子: public interface IFirst { int asd { get; set; } } public interface ISecond { int zxc { get; set; } } public class MyClass { public class PropertyClass : IFirst { pub

我编写了一个嵌套类,用作属性包。这个类被用作我命名为
Properties
的属性。我想通过接口扩展属性的数量

我写了这个例子:

public interface IFirst {
    int asd { get; set; }
}

public interface ISecond {
    int zxc { get; set; }
}

public class MyClass {
    public class PropertyClass : IFirst {
        public int asd {
            get {
                throw new NotImplementedException();
            }
            set {
                throw new NotImplementedException();
            }
        }
    }

    public PropertyClass Properties; 
}

public class MyNextClass : MyClass {
    public class PropertyClass : MyClass.PropertyClass, ISecond {
        public int zxc {
            get {
                throw new NotImplementedException();
            }
            set {
                throw new NotImplementedException();
            }
        }
    }

    public void test() {
        Properties.zxc = 5; // Here is problem
    }
}
但在这种情况下,我无法读取/写入新属性
zxc

我认为,因为这仍然是从父类读取
Properties
类型-
MyClass.PropertyClass
,而不是
MyNextClass.PropertyClass

我想在不创建新属性或隐藏现有属性的情况下扩展它


您有什么建议吗?

您必须确保父类实现这两个接口,或者必须在嵌套子类型的子类中创建一个新的静态成员。正如您猜测的那样,
属性被声明为父嵌套类型,并且在子类中声明一个新类型(从父嵌套类型派生的同名类型)不会改变这一点。

好吧,这取决于您试图实现的方法可能有所不同。例如,使用抽象类可能会满足您的需要。像这样:

公共接口IFirst
{
int asd{get;set;}
}
公共接口等秒
{
int zxc{get;set;}
}
公共抽象类MyAbstractClass,其中T:class
{
公共抽象T属性{get;set;}
}
公共类MyClass:MyAbstractClass
{
公共类属性类:IFirst
{
公共图书馆
{
获取{抛出新的NotImplementedException();}
设置{抛出新的NotImplementedException();}
}
}
公共重写MyClass.PropertyClass属性
{
获取{抛出新的NotImplementedException();}
设置{抛出新的NotImplementedException();}
}
}
公共类MyNextClass:MyAbstractClass
{
公共类PropertyClass:MyClass.PropertyClass,ISecond
{
公共int zxc
{
获取{抛出新的NotImplementedException();}
设置{抛出新的NotImplementedException();}
}
}
公共覆盖MyNextClass.PropertyClass属性
{
获取{抛出新的NotImplementedException();}
设置{抛出新的NotImplementedException();}
}
公开无效测试()
{
Properties.zxc=5;
}
}

这可以工作,但也打破了从
MyClass
MyNextClass
的继承链。话虽如此,不知道更多,那很好。@dlev是的,我知道这不完全是@nosbor所要求的……但正如你所说,不知道更多,我们所能做的就是为一个可能的问题提出可能的解决方案:)糟糕的新。。。当我回到家并尝试使用您的解决方案时,我遇到了错误:错误1“MyNextClass”未实现继承的抽象成员“MyAbstractClass.Properties.set”不,它应该可以工作。请稍等,我将尝试查找问题。@nosbor Done(已修复源代码)。我在
MyClass
中实现了属性,但在
MyNextClass
中忘记了这样做。它现在编译:)