如何比较声明为type的两个对象的类型.
我想知道两个对象是相同类型还是来自同一个基类.
任何帮助表示赞赏.
例如
private bool AreSame(Type a, Type b) {
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*lla 86
说a并且b是两个对象.如果要查看是否a和b是否在同一继承层次结构中,请使用Type.IsAssignableFrom:
var t = a.GetType();
var u = b.GetType();
if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
// x.IsAssignableFrom(y) returns true if:
// (1) x and y are the same type
// (2) x and y are in the same inheritance hierarchy
// (3) y is implemented by x
// (4) y is a generic type parameter and one of its constraints is x
}
Run Code Online (Sandbox Code Playgroud)
如果你想检查一个是否是另一个的基类,那么试试吧Type.IsSubclassOf.
如果您知道特定的基类,那么只需使用is关键字:
if (a is T && b is T) {
// Objects are both of type T.
}
Run Code Online (Sandbox Code Playgroud)
否则,您将必须直接遍历继承层次结构.
Ada*_*son 32
但是,这个想法存在一些问题,因为每个对象(实际上,每种类型)都有一个共同的基类Object.你需要定义的是你要继续进行的继承链的距离(无论它们是相同的还是它们具有相同的直接父级,或者一个是另一个的直接父级,等等)并执行检查那样.IsAssignableFrom对于确定类型是否彼此兼容非常有用,但如果它们具有相同的父级(如果这就是您所追求的),则无法完全确定.
如果您的严格标准是该函数应返回true,如果......
你可以用
private bool AreSame(Type a, Type b)
{
if(a == b) return true; // Either both are null or they are the same type
if(a == null || b == null) return false;
if(a.IsSubclassOf(b) || b.IsSubclassOf(a)) return true; // One inherits from the other
return a.BaseType == b.BaseType; // They have the same immediate parent
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 13
如果您希望两个对象实例属于某种类型,也可以使用"IS"关键字.这也可用于将子类与父类以及实现接口等的类进行比较.这不适用于Type类型的类型.
if (objA Is string && objB Is string)
// they are the same.
public class a {}
public class b : a {}
b objb = new b();
if (objb Is a)
// they are of the same via inheritance
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75617 次 |
| 最近记录: |