【发布时间】:2014-06-25 20:41:46
【问题描述】:
我正在使用反射来设置对象的属性。如果任何 setter 抛出异常,则进行 SetValue 调用的代码不会捕获该异常。 Visual Studio 告诉我该异常未被用户代码捕获。
例如,假设在下面的示例中,“target”变量引用的对象的 Title 属性设置器会抛出 ArgumentException。
看调用栈,好像下面的sn-p和setter之间有非托管代码。
谁能解释一下(&谢谢!):
- 首先为什么会发生这种情况?
- 有没有不重新考虑程序逻辑的简单方法来修复它?
这是我的代码:
try
{
prop.SetValue(target, attr.Value); // target does have a "Title" property
// attr.Value == "Title"
// the setter throws an ArgumentException
}
catch (Exception ex) // No exception is ever caught.
{
errors.Add(ex.Message);
}
下面是我想要设置的众多属性之一的代码: 公共字符串标题 { 得到 { 返回这个.title; }
set
{
if (string.IsNullOrEmpty(value) || value.Length < 1 || value.Length > 128)
{
throw new ArgumentException("Title must be at least 1 character and cannot be longer than 128 characters.");
}
this.title = value;
}
}
【问题讨论】:
-
然后显示此 Title 属性代码...
-
SSCCE 会有所帮助。 sscce.org
-
另外,您不应假设已填充
InnerException。可能是null。使用ex.ToString()获取“异常类型希望您看到的所有内容,包括内部异常” -
请在此处解释为什么要使用反射
-
您确定这不仅仅是调试器设置为停止所有异常,无论它们是否由用户处理? ArgumentException 告诉你什么?
标签: c# reflection