比较C#中包括基类型在内的类型

本文关键字:类型 包括基 比较 | 更新日期: 2024-09-08 07:41:24

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

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,但没有最简单的方法来匹配类型,包括它的基类型树吗?

比较C#中包括基类型在内的类型

您应该做:

if (e is CommunicationException)

是操作员