C# Get subclass attribute value

不问归期 提交于 2019-12-25 04:09:06

问题


I'm trying to make this:

class A { 
   //attibutes
}

class B : A {
   public int classBAttribute = 5;
   // other attributes and methods
}

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

回答1:


You cannot do this -- there is no magical way to create derived objects from base objects in general.

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
}

which you can then use as

var b = new B(a);

Of course after this a and b will be completely different objects; changing one will not affect the other.

You should also get the terminology right in order to avoid confusion: classBAttribute is not an attribute, it is a field.




回答2:


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?

How would your program know an instance of A is actually of type B?

An instance of B could be used as A (as B is a specialization of A), but the opposite is not possible.




回答3:


Maybe I don't fully understand the question or the answers, but...

Casting an A to a B should work (as long as the A is actually (also) a B).

A a = Application.GetA();
if(a is B)
{
    B b = (B)a;
    DoSomething(b.classBAttribute);
}
else
{
    // TODO: Some fallback strategy or exception (?)
}


来源:https://stackoverflow.com/questions/17828888/c-sharp-get-subclass-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!