gpt4 book ai didi

c# - 使用 ExceptionDispatchInfo.Capture 时获取 "not all code paths return a value"

转载 作者:行者123 更新时间:2023-11-30 22:00:50 28 4
gpt4 key购买 nike

我正在研究一种使用反射来调用另一个方法的方法。但是,“其他方法”可能会引发异常,我想用它的原始堆栈信息和 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 方法(根据编译器)并不总是返回值。我可以在 ExceptionDispatchInfo.Capture 之后添加一个 return false 但我想知道是否有更好的方法来实现同样的事情。无需编写多余的 return false

我知道这是一个挑剔的问题,但我忍不住想知道。另外,冗余代码让我很痒 :P

最佳答案

还有另一种选择:您可以添加一个冗余的throw;,而不是添加一个冗余的return false;。然后您不需要弥补返回值。 (好的,对于 bool 来说没什么大不了的)

关于c# - 使用 ExceptionDispatchInfo.Capture 时获取 "not all code paths return a value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233240/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com