C# Get subclass attribute value

2019-09-05 03:45发布

问题:

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 (?)
}