我正在研究一种使用反射来调用另一种方法的方法。那"其他方法"但是,可以抛出一个异常,我想用它的原始堆栈信息和InnerException
传播该异常。这只是因为使用反射的方法不应该处理异常,调用者应该。
这是代码的简化版本:
public static bool Test() {
try {
return (bool) typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
} catch(TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}
public static bool OtherMethod() {
throw new InvalidOperationException();
}
该代码显然不会编译,因为Test
方法(根据编译器)并不总是返回值。
我可以在return false
之后添加ExceptionDispatchInfo.Capture
,但我想知道是否有更好的方式来实现同样的目标。无需编写冗余return false
。
我知道这是一个挑剔的问题,但我无法理解。另外,冗余代码给了我一个痒:P
答案 0 :(得分:2)
还有一个选项:您可以添加冗余return false;
,而不是添加冗余throw;
。
然后,您不需要补偿返回值。 (好吧,bool
)
答案 1 :(得分:1)
最简单的解决方案是不会为您提供冗余或重复的代码,只是将事物放入try
实际将要抛出的内容中。创建bool
,为其分配false
并将其返回都是安全的"操作,请将它们留在try
。
public static bool Test()
{
bool returnValueOfInvoke = false;
try
{
returnValueOfInvoke = (bool)typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
}
catch(TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
return returnValueOfInvoke;
}
public static void OtherMethod()
{
throw new InvalidOperationException();
}