目前我正在使用这种方法将异常转换为将原始异常消息转换为英语的异常:
C#:
[DebuggerStepThrough()]
[Extension()]
public Exception ToEnglish<T>(T ex) where T : Exception
{
CultureInfo oldCI = Thread.CurrentThread.CurrentUICulture;
Exception exEng = default(Exception);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
// Instance Exception one time to retrieve an English message.
exEng = (Exception)Activator.CreateInstance(ex.GetType);
// Instance Exception a second time to pass additional parameters to its constructor.
exEng = (Exception)Activator.CreateInstance(ex.GetType, new object[] {
exEng.Message,
ex
});
Thread.CurrentThread.CurrentUICulture = oldCI;
return exEng;
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//=======================================================
Vb.Net:
<DebuggerStepThrough>
<Extension>
Public Function ToEnglish(Of T As Exception)(ByVal ex As T) As Exception
Dim oldCI As CultureInfo = Thread.CurrentThread.CurrentUICulture
Dim exEng As Exception
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US")
' Instance Exception one time to retrieve an English message.
exEng = DirectCast(Activator.CreateInstance(ex.[GetType]), Exception)
' Instance Exception a second time to pass additional parameters to its constructor.
exEng = DirectCast(Activator.CreateInstance(ex.[GetType], New Object() {exEng.Message, ex}), Exception)
Thread.CurrentThread.CurrentUICulture = oldCI
Return exEng
End Function
(我知道有些异常消息只是用英语部分定义)
但是,我对结果并不完全满意,因为我首先没有返回相同的运行时类型,其次是结果异常的堆栈跟踪是空的,所以我需要保留生成的异常的InnerException
属性中的原始异常的信息。
然后,我想改进功能,以满足那里的requeriments:
FileNotFoundException
)。TargetSite
属性)。我不确定第2点是否可以完成,因为可能的堆栈限制?,无论如何我要知道,我怎么能做这两件事。