[英]Getting the sub-class type
I have 3 classes: 我有3节课:
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
. 但是我意识到,
if (obj is A)
,即使我的obj
是class B
也将被评估为true
。 Is there a way to write the statement such that it evaluates to true if and only if obj
is of class B
? 有没有一种方法可以编写这样的语句:当且仅当
obj
是class B
,它的评估结果才为true?
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
和typeof
GetType is a method on object.
GetType是对象上的方法。 It provides a Type object, one that indicates the most derived type of the object instance.
它提供了一个Type对象,该对象指示对象实例的最派生类型。
and 和
Typeof returns Type objects.
Typeof返回Type对象。 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
typeof运算符是表达式的一部分,该表达式获取类或值类型的Type指针
Try like this 这样尝试
if(obj.GetType() == typeof(A)) // do something
else if(obj.GetType() == typeof(B)) //do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.