简体   繁体   English

是否可以通过构造函数为所有子类更新抽象基类上的泛型属性?

[英]Is it possible to update a generic property on an abstract base class via the constructor for all sub-classes?

This may represent poor design, but if you have a generic property in an abstract class that you wish to set via the constructor, can you set the type and value in not only a direct sub-class, but also sub-classes of the subclass? 这可能代表较差的设计,但是如果您希望通过构造函数在抽象类中具有泛型属性,则不仅可以在直接子类中而且可以在子类的子类中设置类型和值?

public interface IFirst { }
public interface ISecond { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IFirst> {
    public B(IFirst someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(IFirst someProperty) : base(someProperty) {
        //What if I wanted to pass in ISecond as a type to SomeProperty by instantiating this class?
    }
}

For all sub-classes of B, I'm locked into using IFirst as the type passed into the constructor. 对于B的所有子类,我只能使用IFirst作为传递给构造函数的类型。

Is there a design pattern or solution that solves this problem? 是否有解决此问题的设计模式或解决方案?

Thanks, 谢谢,

You could use another interface to derive the two defined interfaces from: 你可以使用其他interface派生的两个定义的interfaces从:

public interface IBase {}
public interface IFirst : IBase { }
public interface ISecond : IBase { }

public abstract class A<T> {
    public T SomeProperty { get; }

    protected A(T someProperty) {
        SomeProperty = someProperty;
    }
}

public class B : A<IBase> {
    public B(IBase someProperty) : base(someProperty) {
    }
}

public class C : B {
    public C(ISecond someProperty) : base(someProperty) {
        //Works now
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM