简体   繁体   中英

C# Upcasting / Polymorphism Issue

I believe this question is fairly basic but I am having trouble finding an answer to this question. In C# let's say I have 3 classes: A, B, C

B derives from A

C derives from B

Now, if I wanted a list or array of objects of type class A but wanted the array to be able to house objects of type B and C this is no problem... I could do something like this:

A[] myArrayofAtypes;

However let's say I make the first element of this array of type C. If type C has a variable defined in its class definition that ONLY exists in class C's class definition... how do I access that variable from the array? I can't just do A[0].MyVariableGetter as that variable does not exist in the base class, A.

Any suggestions?

You have to downcast it:

C c = (C)myArrayofAtypes[0];
var v = c.MyVariableGetter;

You have to type cast it to type c and access the member.

If (arr[i] is c)
{
    ((C)arr[0]).member = value;
 }

Instead of casting as 'king.code' has suggested like this I would use these pretty C# operators which are 'is' and 'as'.

public void CallIfTypeC(A a)
{
    if (a is C)
    {
        C c = a as C;
        c.DoAction();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM