比较类型,包括 C# 中的基本类型

Fan*_*nda 4 c# comparison types

如果我捕获异常,它也会捕获类型及其基本类型:

try
{
    throw new EndpointNotFoundException(...);
}
catch (CommunicationException e)
{
    // EndpointNotFoundException is caught (inherits from CommunicationException)
}
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能以同样的方式比较类型呢?

var e = new EndpointNotFoundException(...);
if (e.GetType() == typeof(CommunicationException)) // is not true
{

}
Run Code Online (Sandbox Code Playgroud)

我知道我可以观看Type.BaseType,但是没有最简单的方法来匹配包括其基本类型树在内的类型吗?

xan*_*tos 6

你应该做:

if (e is CommunicationException)
Run Code Online (Sandbox Code Playgroud)

是运算符