【问题标题】:How to convert an abstract base class to generic derived class and access properties of the child class?如何将抽象基类转换为泛型派生类并访问子类的属性?
【发布时间】:2014-11-26 16:33:59
【问题描述】:

我的类层次结构如下:

[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....

    }
}

现在我将 ChildClass2 实例化为 baseClass 类型,如下所示:

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

如何将 baseClass 转换为 ChildClass2 类型以便访问 baseClass.Property2?

我尝试了类似 (ChildClass2)baseClass.Property2 的方法不起作用。

【问题讨论】:

  • BaseClass baseClass = ChildClass2("test1", "test2"); 无法编译,因为您没有为 T 提供类型。
  • 我认为它基于参数类型,但是在问题中修复了它。

标签: c# generics inheritance casting


【解决方案1】:
BaseClass baseClass = ChildClass2<string>("test1", "test2");
string value = ((ChildClass2<string>) baseClass).Property2;

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多