使用 ExceptionDispatchInfo.Capture 时获得 "not all code paths return a value"

Getting "not all code paths return a value" when using ExceptionDispatchInfo.Capture

我正在研究一种使用反射来调用另一个方法的方法。但是,"other method" 可以抛出异常,我想用它的原始堆栈信息和 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 一个值。 我可以在 ExceptionDispatchInfo.Capture 之后添加一个 return false 但我想知道是否有更好的方法来实现同样的事情。不写多余的 return false.

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

不会给您冗余或重复代码的最简单解决方案是只将实际要抛出的内容放入 try 中。创建你的 bool,分配它 false 并返回它都是 "safe" 操作,所以把它们放在 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();
}

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