我有这种情况
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>
答案 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!";
}