如何使用“泛型”类型构建一个类并将其实例化为派生类?

时间:2014-01-20 16:25:18

标签: c# oop inheritance

我有这种情况

public class CustomClass
{
    public string stringTest { get; set; }
    public int numberTest { get; set; }
    public (xy) foo { get; set; }
}

这将是我的主要课程,然后:

public class Base
{
    public string somePropery { get; set; }
}

public class Derived : Base
{
    public string someOtherProperty { get; set;}
}

public class Derived2 : Base
{
    public string someHappyProperty { get; set;}
}

我想这样做:

CustomClass test = new CustomClass()
{
    foo = new Derived()
}

test.foo.someOtherProperty = "Wow!";

CustomClass test = new CustomClass()
{
    foo = new Derived2()
}

test.foo.someHappyProperty = "Wow!";

显然我无法将foo的类型设置为Base,我宁愿避免使用dynamic类型,处理此问题的正确方法是什么?< / p>

2 个答案:

答案 0 :(得分:2)

CustomClass通用:

public class CustomClass<T>
    where T : Base
{
    public string stringTest { get; set; }
    public int numberTest { get; set; }
    public T foo { get; set; }
}

您现在可以写:

CustomClass<Derived> test = new CustomClass<Derived>()
{
    foo = new Derived()
};


test.foo.someOtherProperty = "Wow!";

答案 1 :(得分:-1)

  

显然,我无法将foo的类型设置为Base

为什么不呢?

如果您知道它将是Derived,请将其类型设置为Derived。如果不这样做,请将其设置为Base。如果您以后想查看是否 Derived并在其上设置Derived个特定成员,则可以使用is关键字:

if (test.foo is Derived)
{
    ((Derived) test.foo).someOtherProperty = "Wow!";
}