0

私はこれを作ろうとしています:

class A { 
   //attibutes
}

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

私の質問は、A クラスのインスタンスがある場合、B クラスのインスタンスを取得したり、その属性にアクセスしたりするにはどうすればよいですか?

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
4

3 に答える 3

1

質問や回答の意味がよくわからないかもしれませんが...

Aanから a へのキャストは機能するB はずAです (が実際に (また) a である限りB)。

A a = Application.GetA();
if(a is B)
{
    B b = (B)a;
    DoSomething(b.classBAttribute);
}
else
{
    // TODO: Some fallback strategy or exception (?)
}
于 2013-07-24T09:23:19.457 に答える