如果我捕获异常,它也会捕获类型及其基类型:
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)
是操作员