开发者

C#: Test if a class in an instance of a super class instead of a subclass

开发者 https://www.devze.com 2023-02-23 12:06 出处:网络
I have a class, which has a bunch of subclasses that inherit from it. How can I test to see whether an object is an instance of that super class, and not of any of the derived classes?

I have a class, which has a bunch of subclasses that inherit from it. How can I test to see whether an object is an instance of that super class, and not of any of the derived classes?

Example:

I have a Vehicle class, and it has several classes that inherit from it, like Car, Motorcycle, Bicycle, Truck, etc.

Assuming this, how do I test to see if a V开发者_高级运维ehicle object is really of the class Vehicle, and not Car or Bicycle? (Since a Car and a Bicycle are in this case an instance of the Vehicle class, too.)


if (theObject.GetType() == typeof(Vehicle))
{
   // it's really a Vehicle instance
}


Use Object.GetType() to determine the concrete type of the object.

Vehicle v = GetVehicle();

if(v.GetType() == typeof(Vehicle))
{
}


You can use:

bool isSuper = instance.GetType() == typeof(Vehicle);
0

精彩评论

暂无评论...
验证码 换一张
取 消