【发布时间】:2014-06-03 20:42:26
【问题描述】:
我有一种情况,即在来自 classA 的 PropertyInfo 上的 SetValue 周围放置一个 try-catch 不会捕获 classA 属性的设置器抛出的异常。我该如何陷害这个案子?示例如下:
public class classA
{
private string _ID;
public string ID
{
get { return _ID; }
set
{
if (_ID == null) _ID = value;
else throw new InvalidOperationException();
}
}
}
public class classB
{
public void DoMagic()
{
classA MyA = new classA();
PropertyInfo pi = GetPropertyInfoForProperty(typeof(classA), "ID");
try
{
pi.SetValue(MyA, "This works fine", null);
}
catch { }
///MyA.ID = "The first time you set it everything is cool.";
try
{
MyA.ID = "This throws a handled exception.";
}
catch { }
try
{
pi.SetValue(MyA, "This Throws and Unhandled Exception", null);
}
catch { }
}
private PropertyInfo GetPropertyInfoForProperty(Type type, string p)
{
foreach (var pi in type.GetProperties())
if (pi.Name == p)
return pi;
return null;
}
}
【问题讨论】:
-
你能发布没有被捕获的异常细节吗?您是否看到诸如“调用目标抛出异常”之类的消息?顺便说一句,我无法在 LinqPad 中重现该问题。
-
您是否确定 GetPropertyInfoForProperty() 方法没有抛出异常?第一次使用 SetValue 反射是否有效?
-
请显示函数“GetPropertyInfoForProperty”的代码
-
消息是 InvalidOperationException is unhandled by user code {"Operation is not valid due to the current state of the object."} 这是我故意抛出的异常。
-
不是答案,但您可以将方法更改为
return type.GetProperty(p);
标签: c#