C#获取子类属性值 [英] C# Get subclass attribute value
问题描述
我正在努力做到这一点:
I'm trying to make this:
class A {
//attibutes
}
class B : A {
public int classBAttribute = 5;
// other attributes and methods
}
我的问题是,如果我有一个A类的实例,如何获得B类的实例或访问他的属性?
My question is this if I have an instance of A class how can i get the instance of the B class or access his attributes?
B b = new B();
Application.Add(b);
//other form
A a = Application.GetA();
B b = getBFromA(a);// ??? Note: B b = a as B; does't work i tried
推荐答案
您无法做到这一点-通常,没有神奇的方法可以从基础对象创建派生对象.
You cannot do this -- there is no magical way to create derived objects from base objects in general.
要启用这样的方案类,B
将需要定义一个接受A
自变量的构造函数:
To enable such a scheme class B
would need to define a constructor that accepts an A
argument:
public B(A a)
{
// do whatever makes sense to create a B from an A
}
然后您可以将其用作
var b = new B(a);
当然,在这之后a
和b
将是完全不同的对象;改变一个不会影响另一个.
Of course after this a
and b
will be completely different objects; changing one will not affect the other.
您还应该正确使用术语以避免混淆:classBAttribute
不是字段.
You should also get the terminology right in order to avoid confusion: classBAttribute
is not an attribute, it is a field.
这篇关于C#获取子类属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!