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

标签 c# .net exception reflection byref

此代码输出“输出值”。

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();
  }
}

但是这个没有。

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();
  }
}

使用反射时,如何同时获得“输出值”和异常

最佳答案

异常绕过 MethodInfo.Invoke() 中的代码,该代码将 [out] 值从堆栈帧复制回对象数组。 Invoke() 创建的堆栈帧上的值的行为与第一个代码段中的行为一样。但这就是相似之处结束的地方。

关于c# - 如何从抛出异常的方法中通过 out/ref 参数获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100725/

相关文章:

c# - 库中的 ConfigureAwait(false) 是否会丢失调用应用程序的同步上下文?

c# - 如何使用抛出 InvalidOperationException 的计时器更改标签内容

c# - 在 C# SQL 查询中,Parameters.Add() 比直接在查询中嵌入值有什么优势?

android - 无法使用处理程序解决 CalledFromWrongThreadException

java - NotifyAll,IllegalMonitorStateException

c# - cocoa 的属性网格

c# - Form.ShowDialog() 不破坏句柄

c# - c# 中的正则表达式 - 英国邮政编码

c# - Svn 外部和 C# 程序集 - 不兼容?

c# - 使用 Ado.Net 存储过程时是否可靠地抛出异常?