如何从抛出异常的方法中通过out/ref参数获取值?

mat*_*llo 12 .net c# reflection exception byref

此代码输出"out value".

class P
{
  public static void Main()
  {
    string arg = null;
    try
    {
      Method(out arg);
    }
    catch
    {
    }
    Console.WriteLine(arg);
  }
  public static void Method(out string arg)
  {
    arg = "out value";
    throw new Exception();
  }
}
Run Code Online (Sandbox Code Playgroud)

但这一个没有.

class P
{
  public static void Main()
  {
    object[] args = new object[1];
    MethodInfo mi = typeof(P).GetMethod("Method");
    try
    {
      mi.Invoke(null, args);
    }
    catch
    {
    }
    Console.WriteLine(args[0]);
  }
  public static void Method(out string arg)
  {
    arg = "out value";
    throw new Exception();
  }
}
Run Code Online (Sandbox Code Playgroud)

如何在使用反射时获得"out value"和异常

Guf*_*ffa -1

如果方法抛出异常,则 out 参数未定义。您可以通过在第一个示例中不将其初始化为 null 来看到这一点,然后代码将无法编译。

因此,如果 Invoke 方法引发异常,则不返回未定义的值是有意义的。

  • >>“如果方法抛出异常,则 out 参数未定义。” 这是为什么?是的,如果您删除初始化,那么代码将无法编译。但这不是因为 Method() 中存在 throw ,而是因为 Main 中的空 catch 块,即并非所有执行路径在实际使用之前都会初始化 arg 值。 (2认同)