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

C# 比较C中的类型,包括基类型#,c#,types,comparison,C#,Types,Comparison,如果捕获异常,它也会捕获类型及其基类型: try { throw new EndpointNotFoundException(...); } catch (CommunicationException e) { // EndpointNotFoundException is caught (inherits from CommunicationException) } 但是我怎样才能以同样的方式比较类型呢 var e = new EndpointNotFoundExceptio

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

try
{
    throw new EndpointNotFoundException(...);
}
catch (CommunicationException e)
{
    // EndpointNotFoundException is caught (inherits from CommunicationException)
}
但是我怎样才能以同样的方式比较类型呢

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

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

您应该:

if (e is CommunicationException)

非常好。谢谢。@Augusto否,这是用于类型与类型的比较。这里他谈到的是实例与类型的比较。但是肯定还有几十个关于is/as操作符的问题。@xanatos是的,你是对的;)虽然公认的答案涉及is和as操作员,但问题并非完全相同。:-)我在寻找,真的。。。