获取 sub-class 类型

Getting the sub-class type

我有3个类:

class O
{
}

class A : O
{
}

class B : A
{
}

当我调用我的代码时:

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
    }
}

但是我意识到即使我的 objclass Bif (obj is A) 也会被评估为 true。有没有一种方法可以编写语句,当且仅当 obj 属于 class B?

时,它的计算结果为真

有两种方法GetTypetypeof

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

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

像这样尝试

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

为什么不在基类中定义一个虚函数 class 并在派生类型中覆盖它,在不同的情况下做你需要的?

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
    }
}

然后你的循环变成

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