如何检查一个对象是否*正好*一个类,而不是一个派生的类?

Fer*_*anB 4 c# inheritance

有什么方法可以确定一个对象是否完全是一个类而不是派生的一个类?

例如:

class A : X { }

class B : A { }
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

bool isExactlyA(X obj)
{
   return (obj is A) && !(obj is B);
} 
Run Code Online (Sandbox Code Playgroud)

当然,如果有更多的派生类A我必须添加条件.

Eri*_*ert 10

推广窃笑者的答案:

public static bool IsExactly<T>(this object obj) where T : class
{
  return obj != null && obj.GetType() == typeof(T);
}
Run Code Online (Sandbox Code Playgroud)

现在你可以说

if (foo.IsExactly<Frob>()) ...
Run Code Online (Sandbox Code Playgroud)

警告:明智地使用对象的扩展方法.根据您使用此技术的广泛程度,这可能是不合理的.


sni*_*ker 5

在您的特定实例中:

bool isExactlyA(X obj)
{
   return obj.GetType() == typeof(A);
}
Run Code Online (Sandbox Code Playgroud)