开发者

C#: How to check types of two instances

I am having trouble getting the right syntax for this.

Say I have two instantiated objects, obj1 and obj2.

Now, I want to check two things:

1) Is the type of obj1 is a subclass of the type of obj2.

2) Is the type of obj1 is the same as the type of obj2.

I'm pretty sure I can achieve 1) by just doing

obj1.GetType().IsSubclassOf(obj2.GetType())

But will the above return true if obj1 and obj2 are of the sam开发者_如何学Ce type?


MSDN says it will return false if obj1 and obj2 are the same class http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx

You can just do

obj1.GetType().IsSubclassOf(obj2.GetType()) || obj1.GetType() == (obj2.GetType()


When in doubt, consult the documentation (emphasis mine):

Return Value: true if the Type represented by the c parameter and the current Type represent classes, and the class represented by the current Type derives from the class represented by c; otherwise, false.

This method also returns false if c and the current Type represent the same class.

If you want to check if two types are the same, you can just compare their Types:

obj1.GetType() == obj2.GetType()


obj2.GetType().IsAssignableFrom(obj1.GetType())
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜