【发布时间】:2014-06-26 20:43:30
【问题描述】:
对 SetValue 使用属性反射时,该属性会引发 TargetInvocationException。但是,由于对 SetValue 的调用是一个调用,因此会捕获异常并且不会在属性中进行处理。有没有办法处理属性中的目标异常并只在主程序中抛出它?
我希望这个 throw 就像我只是进行了一个方法调用,而不是一个调用。
编辑澄清:
我遇到的问题是,在反射类中,我收到一条调试消息,上面写着“用户代码未处理异常”。我必须“继续”调试会话,内部异常是“真正的”异常。这只是意料之中吗?我不想收到警告(也不想隐藏警告),我希望代码修复警告。
public class reflect
{
private int _i;
public int i
{
get { return _i; }
set
{
try{throw new Exception("THROWN");}
catch (Exception ex)
{ // Caught here ex.Message is "THROWN"
throw ex; // Unhandled exception error DONT WANT THIS
}
}
}
}
class Program
{
static void Main(string[] args)
{
reflect r = new reflect();
try
{
r.GetType().GetProperty("i").SetValue(r, 3, null);
}
catch(Exception ex)
{ // Caught here, Message "Exception has been thrown by the target of an invocation"
// InnerMessage "THROWN"
// WANT THIS Exception, but I want the Message to be "THROWN"
}
}
}
【问题讨论】:
-
这不是正常意义上的警告(即在编译时显示的东西)——它只是调试器闯入(这根本不是 在您的第一个版本中清除)。我相信这是另一个 SO 问题的重复,但可能很难找到。
标签: c# targetinvocationexception