【发布时间】:2011-01-07 05:28:25
【问题描述】:
此代码输出“输出值”。
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();
}
}
使用反射时,如何同时获得“输出值”和异常?
【问题讨论】:
-
好问题。但是如果方法抛出,你不应该依赖
out值。 -
+1,好问题,当然我必须尝试一下:) 我推测您的原始变量没有传递给调用的函数,它得到一个副本,并且该副本得到成功完成后反射回原件(当然不会发生)。
-
@slugster:你的猜测是正确的。我怀疑没有任何方法可以通过反射来做到这一点。
标签: c# .net exception reflection byref