简体   繁体   中英

how to check the Type used by a generic class

Consider the case where you have various classes derived from MyFaultBase . So when your web service needs to indicate fault it throws an exception of type FaultException<MySpecificFault> .

After catching this exception, how can you determine whether the FaultException<T> is bound to a class derived from MyFaultBase ?

In a global way :

    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]);
    }

You can get the generic type arguments using Type.GetGenericArguments() .

Then your IsExceptionBoundToType method may look something like this:

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;
}

As far as I can tell, there is no simple way to is-check a generic class; likely due to the flexibility of the generic parameter. Here is a solution:

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 the exception and check it like this:

catch (Exception ex)
{
   if ((ex is FaultException) && IsExceptionBoundToType(ex, typeof(MyFaultBase)))
   {
      // do something
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM