0

考虑从MyFaultBase. 因此,当您的 Web 服务需要指示故障时,它会引发类型异常FaultException<MySpecificFault>

捕获此异常后,如何确定 是否FaultException<T>绑定到派生自的类MyFaultBase

4

3 回答 3

3

在全球范围内:

    public class SpecificClass : BaseClass
    {
    }

    public class BaseClass
    {
    }

    public class TemplatedClass<T>
    {
    }

    static void Main(string[] args)
    {
        var templateInstance = new TemplatedClass<SpecificClass>();
        var @true = typeof (BaseClass).IsAssignableFrom(templateInstance.GetType().GetGenericArguments()[0]);

        var templateInstance2 = new TemplatedClass<int>();
        var @false = typeof (BaseClass).IsAssignableFrom(templateInstance2.GetType().GetGenericArguments()[0]);
    }
于 2013-07-04T16:38:38.667 回答
2

您可以使用Type.GetGenericArguments().

那么你的IsExceptionBoundToType方法可能看起来像这样:

public static bool IsExceptionBoundToType(FaultException fe, Type checkType)
{
    bool isBound = false;
    Type feType = fe.GetType();
    if (feType.IsGenericType && feType.GetGenericTypeDefinition() == typeof(FaultException<>))
    {
        Type faultType = feType.GetGenericArguments()[0];
        isBound = checkType.IsAssignableFrom(faultType);
    }

    return isBound;
}
于 2013-07-04T16:51:04.573 回答
0

据我所知,没有简单的方法来检查泛型类。可能是由于泛型参数的灵活性。这是一个解决方案:

public static bool IsExceptionBoundToType(FaultException fe, Type checkType)
{
   bool isBound = false;

   // Check to see if the FaultException is a generic type.
   Type feType = fe.GetType();
   if (feType.IsGenericType && feType.GetGenericTypeDefinition() == typeof(FaultException<>))
   {
      // Check to see if the Detail property is a class of the specified type.
      PropertyInfo detailProperty = feType.GetProperty("Detail");
      if (detailProperty != null)
      {
         object detail = detailProperty.GetValue(fe, null);
         isBound = checkType.IsAssignableFrom(detail.GetType());
      }
   }

   return (isBound);
}

捕获异常并像这样检查它:

catch (Exception ex)
{
   if ((ex is FaultException) && IsExceptionBoundToType(ex, typeof(MyFaultBase)))
   {
      // do something
   }
}
于 2013-07-04T16:22:34.193 回答