[英]how to check the Type used by a generic class
Consider the case where you have various classes derived from MyFaultBase
. 考虑一下您具有从
MyFaultBase
派生的各种类的情况。 So when your web service needs to indicate fault it throws an exception of type FaultException<MySpecificFault>
. 因此,当您的Web服务需要指示故障时,它将引发
FaultException<MySpecificFault>
类型的异常。
After catching this exception, how can you determine whether the FaultException<T>
is bound to a class derived from MyFaultBase
? 捕获此异常之后,如何确定
FaultException<T>
是否绑定到从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()
. 您可以使用
Type.GetGenericArguments()
获得泛型类型参数。
Then your IsExceptionBoundToType
method may look something like this: 然后,您的
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;
}
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.