那么,你会怎么做的详细介绍,如果你知道它的方式输入?
因为它是通用的,所以你必须有一个通用的方法,并使用MethodException,使用FaultException的T作为通用参数的MethodInfo.MakeGenericMethod。既然你不知道在编译时究竟是什么类型,反正你必须在某种意义上对其进行一般编码。
作为一个例子,这里是我写的日志故障的详细信息的方法:
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 })
我打算用DataContractSerializer的,我只需要获取类型的对象,然后我不需要反射。我只需要访问细节获取器而不使用反射,但似乎不可能 – 2009-12-30 15:47:30
您是否阅读过我的代码,因为这正是我正在做的。在我的第二个示例中,faultExceptionType变量是exception.GetType(),然后您会看到我对它调用GetGenericArguments并将它们传递给MakeGenericMethod。我会更新代码以使其更加明显。 – 2009-12-30 20:12:29
是的,我没看过你的代码,但我的观点是,这仍然是使用反射,我没有看到我发布的代码片段的任何优势... – 2009-12-31 07:28:12