简体   繁体   中英

How to convert an abstract base class to generic derived class and access properties of the child class?

I have my class hierarchy as follows:

[DataContract]
[Serializable]
[KnownType(typeof(ChildClass2<>))]
public abstract class BaseClass
{
    protected BaseClass(string property1)
    {
        this.Property1 = property1;
    }

    [DataMember]
    public string Property1 { get; private set; }

    public abstract bool Method1(string inputValue);
}


[DataContract]
[Serializable]
public abstract class ChildClass1<T> : BaseClass
{
    protected ChildClass1(string property1, T property2) : base(property1) 
    {
        this.Property2 = property2;
    }

    [DataMember]
    public T Property2 { get; private set; }
}


[DataContract]
[Serializable]
public class ChildClass2<T> : ChildClass1<T>
{
    public ChildClass2(string proprty1, T property2)
        : base(property1, property2)
    {
    }

    public override bool Method1(string inputValue)
    {
      // Some processing....

    }
}

Now I am instantiating ChildClass2 as baseClass type like below:

BaseClass baseClass = ChildClass2<string>("test1", "test2");

How can I cast baseClass to ChildClass2 type so I can access baseClass.Property2?

I tried something like (ChildClass2)baseClass.Property2 does not work.

BaseClass baseClass = ChildClass2<string>("test1", "test2");
string value = ((ChildClass2<string>) baseClass).Property2;

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