如何检查一个对象是否*正好*一个类,而不是一个派生的类? [英] How to check if an object its *exactly* a class, not a derived one?
本文介绍了如何检查一个对象是否*正好*一个类,而不是一个派生的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以确定某个对象是否完全一个类而不是派生的一个?
There is any way to determine if an object is exactly a class and not a derived one of that?
例如:
class A : X { }
class B : A { }
我可以这样做:
bool isExactlyA(X obj)
{
return (obj is A) && !(obj is B);
}
当然,如果有更多派生类 A
我必须添加和条件。
Of course if there are more derived classes of A
I'd have to add and conditions.
推荐答案
推广窃听器回答:
public static bool IsExactly<T>(this object obj) where T : class
{
return obj != null && obj.GetType() == typeof(T);
}
现在你可以说
if (foo.IsExactly<Frob>()) ...
警告:明智地对对象使用扩展方法。根据您使用此技术的广泛程度,这可能不合理。
Caveat: use extension methods on object judiciously. Depending on how widely you use this technique, this might not be justified.
这篇关于如何检查一个对象是否*正好*一个类,而不是一个派生的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文