[英]How access properties of Inherited classes from abstract class
I am working with a code in which there is an abstract class, eg: 我正在使用一个代码,其中有一个抽象类,例如:
public abstract class AbstractClass
{
...
}
and there are inherited classes from AbstractClass. 并且有来自AbstractClass的继承类。 One object is created depending on user input from one of inherited classes.
根据来自其中一个继承类的用户输入创建一个对象。 Each inherited class has its own properties:
每个继承的类都有自己的属性:
class classOne : AbstractClass
{
...
public int A { get; set;}
public int B { get; set;}
public int C { get; set;}
...
}
class classTwo : AbstractClass
{
...
public int D { get; set;}
public int E { get; set;}
...
}
... Say I want to use functions in that code and I know which object type would be returned. ...说我想在该代码中使用函数,我知道将返回哪种对象类型。 How can I modify the properties of the output object since the program is written in a way that the class of output is only determined when the program is run?
如何修改输出对象的属性,因为程序的编写方式只能在程序运行时确定输出类?
If you know what concrete type you'll have, you can always cast your object: 如果你知道你将拥有什么样的具体类型,你可以随时投射你的对象:
var concreteObject = myObj as classOne;
Or, if you don't know what object type you'll have, you can test for it and then cast: 或者,如果您不知道您将拥有哪种对象类型,则可以测试它然后进行转换:
if (myObj is classOne) {
// Cast to classOne and use
} else if (myObj is classTwo) {
// Cast to classTwo and use
}
Hope this helps answer your question! 希望这有助于回答您的问题!
如果您在运行时知道实例将是特定类型,但您无法向编译器证明它,则可以将其强制转换:
(SomeType)instance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.