好吧,如果你知道它的类型,你会怎么处理细节呢?
因为它是泛型的,所以必须有一个泛型方法,并使用MethodInfo.MakeGenericMethod,使用FaultException的t作为泛型参数。因为您在编译时不知道它是什么类型,所以无论如何,您必须在某种意义上针对它进行一般性的编码。
例如,我写了一个方法来记录故障详细信息:
private static void WriteGenericFaultExceptionDetail<T>(FaultException faultException, StringBuilder faultDetailsBuilder)
{
FaultException<T> faultExceptionWithDetail = (FaultException<T>)faultException;
DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
using(StringWriter writer = new StringWriter(faultDetailsBuilder))
using(XmlWriter xmlWriter = XmlWriter.Create(writer))
{
dataContractSerializer.WriteObject(xmlWriter, faultExceptionWithDetail.Detail);
}
}
然后我这样称呼它:
// NOTE: I actually cache this in a static field to avoid the constant method lookup
MethodInfo writeGenericFaultExceptionDetailMethodInfo = typeof(MyClass).GetMethod("WriteGenericFaultExceptionDetail", BindingFlags.NonPublic|BindingFlags.Static);
Type faultExceptionType = myFaultException.GetType();
writeGenericFaultExceptionDetailMethodInfo.MakeGenericMethod(faultExceptionType.GetGenericArguments()).Invoke(null, new object[] { myFaultException, myTraceBuilder })