我有基类的BaseClass
和派生类 DerivedA
, DerivedB
和 DerivedC
所有继承的BaseClass
。
I have base class BaseClass
and derived classes DerivedA
, DerivedB
, and DerivedC
that all inherit BaseClass
.
我有另一个类, ExternalClass
与接受类型的参数的BaseClass
,但实际上是通过一种方法派生类。什么是这些类 ExternalClass
之间的区别,如果我想在此基础上收到的派生类?
I have another class, ExternalClass
with a method that accepts a parameter of type BaseClass
, but is actually passed a derived class. What is the best way to differentiate between these classes in ExternalClass
if I wanted to perform a different action based on which derived class it received?
我在想这样做一个选择
,但我不完全知道如何。
I was thinking of doing a Select
but I'm not exactly sure how.
您设计的很可能是有缺陷的。你应该考虑的行为的BaseClass
的方法并覆盖它在每一个派生类。你不应该检查对象的实际类型。
Your design is very likely to be flawed. You should consider making the behavior a method of BaseClass
and override it in each derived class. You shouldn't check for the actual type of the object.
也就是说, ExternalClass
应该只是调用的BaseClass
声明的方法无论实际类型。由于该方法是由派生类重写,相应的执行将被调用。
That is, ExternalClass
should just call a method declared in BaseClass
regardless of the actual type. Since the method is overriden by derived classes, the appropriate implementation will be called.
这是说,检查对象是一个类型或其派生类的一个实例,您可以使用是
操作符:
That said, to check if an object is an instance of a type or its derived classes, you can use the is
operator:
if (obj is DerivedA) // C#
If TypeOf obj Is DerivedA Then ' // VB
如果要检查,如果对象是一个特定类型的实例(而不是其派生类型):
If you want to check if the object is an instance of a specific type (and not its derived types):
if (obj.GetType() == typeof(DerivedA)) // C#
If obj.GetType() Is GetType(DerivedA) Then ' // VB