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 方法引发异常,则不返回未定义的值是有意义的。