简体   繁体   中英

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.

Is there a design pattern or solution that solves this problem?

Thanks,

You could use another interface to derive the two defined interfaces from:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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