如何检查一个对象是否*正好*一个类,而不是一个派生的类?
有什么方法可以确定一个对象是否完全是一个类而不是派生的一个类?
例如:
class A : X { } class B : A { }
我可以这样做:
bool isExactlyA(X obj) { return (obj is A) && !(obj is B); }
当然,如果有更多的派生类A
我必须添加和条件。
推广窃笑者的答案:
public static bool IsExactly(this object obj) where T : class { return obj != null && obj.GetType() == typeof(T); }
现在你可以说
if (foo.IsExactly()) ...
警告:明智地使用对象的扩展方法。 根据您使用此技术的广泛程度,这可能不合理。
在您的特定实例中:
bool isExactlyA(X obj) { return obj.GetType() == typeof(A); }
我知道了…
control.GetType() == typeof(Label)
有关typeof
和is
更多信息is
运算符,以及GetType方法。