如何使用"generic"类型构建类并将其实例化到派生类?



我有这种情况

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类型,什么是处理此操作的正确方法?

使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!";

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

为什么不呢?

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

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

最新更新