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 theType
represented by thec
parameter and the currentType
represent classes, and the class represented by the currentType
derives from the class represented byc
; otherwise,false
.This method also returns
false
ifc
and the currentType
represent the same class.
If you want to check if two types are the same, you can just compare their Type
s:
obj1.GetType() == obj2.GetType()
obj2.GetType().IsAssignableFrom(obj1.GetType())
精彩评论