简体   繁体   中英

Getting the sub-class type

I have 3 classes:

class O
{
}

class A : O
{
}

class B : A
{
}

When I call my code:

List<O> myList = new List<O>();
myList.Add(new A());
myList.Add(new B());

foreach (O obj in myList)
{
    if (obj is A)
    {
         // do something
    }
    else if (obj is B)
    {
         //do something
    }
}

However I realized that if (obj is A) will be evaluated to be true even when my obj is of class B . Is there a way to write the statement such that it evaluates to true if and only if obj is of class B ?

Why don't you define a virtual function in the base class and override it in the derived types, doing what you need in the different cases?

class O {
    public virtual void DoSomething() {
        // do smtgh in the 'O' case
    }
}

class A : O {
    public override void DoSomething() {
        // do smtgh in the 'A' case
    }
}

class B : A {
    public override void DoSomething() {
        // do smtgh in the 'B' case
    }
}

Then your loop becomes

foreach (O obj in myList) {
    obj.DoSomething();
}

There are two method GetType and typeof

GetType is a method on object. It provides a Type object, one that indicates the most derived type of the object instance.

and

Typeof returns Type objects. It is often used as a parameter or as a variable or field. The typeof operator is part of an expression that acquires the Type pointer for a class or value type

Try like this

 if(obj.GetType() == typeof(A)) // do something
 else if(obj.GetType() == typeof(B)) //do something

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