简体   繁体   English

C#上载/多态问题

[英]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 在C#中,假设我有3个类别: A, B, C

B derives from A B衍生自A

C derives from B C源自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的对象的列表或数组,但希望该数组能够容纳类型为B和C的对象,这是没有问题的……我可以这样做:

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? 但是,假设我是该类型C的数组的第一个元素。如果类型C在其类定义中定义了一个变量,则该变量仅存在于类C的类定义中……如何从数组访问该变量? I can't just do A[0].MyVariableGetter as that variable does not exist in the base class, A. 我不能只做A[0].MyVariableGetter因为该变量在基类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. 您必须键入强制类型转换才能键入c并访问该成员。

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'. 我不会使用像这样的“ king.code”强制转换,而是使用这些漂亮的C#运算符“ is”和“ as”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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