使用反射,setter会抛出无法捕获的异常

本文关键字:异常 反射 setter | 更新日期: 2023-09-27 18:10:14

我使用反射来设置对象的属性。如果任何setter抛出异常,则调用SetValue的代码不会捕获该异常。Visual Studio告诉我,用户代码未捕获异常。

例如,在下面的例子中,假设"target"变量引用的对象上的Title属性setter抛出一个ArgumentException

查看调用堆栈,似乎在下面的代码片段和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);
}

下面是我想这样设置的许多属性之一的代码:公共字符串标题{得到{返回this.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;
        }
    }

使用反射,setter会抛出无法捕获的异常

EDIT如@Default所述,Framework 4.5确实有一个只有两个参数的过载,所以如果用户正在使用FW 4.5这个答案没有相关性(至少关于PropertyInfo的最后一部分),

你错了,它被困住了,这里有一个例子来证明它:

public class ExceptionGenerator
{
    public static void Do()
    {
        ClassToSet clas = new ClassToSet();
        Type t = clas.GetType();
        PropertyInfo pInfo = t.GetProperty("Title");
        try
        {
            pInfo.SetValue(clas, "test", null);
        }
        catch (Exception Ex)
        {
            Debug.Print("Trapped");
        }
    }
}
class ClassToSet
{
    public string Title {
        set {
            throw new ArgumentException();
        }
    }
}

你做错了什么是获得PropertyInfo, PropertiInfo的SetValue方法期望第三个参数,属性的索引(在你的情况下为空),所以你的"prop"不是PropertyInfo,我认为它是一个FieldInfo,因为它抛出一个未处理的异常。

任何异常都应该被捕获。

参见:https://dotnetfiddle.net/koUv4j

这包括反射调用本身的错误(将属性设置为错误的Type),或者在属性的setter本身中有异常(set抛出)。

这会导致其他地方出错。可能性:

  • 你已经把你的IDE设置为在所有异常情况下停止
  • 异常不会发生在你认为它是(像,在catch,这将是throw)

如果不是,请提供更多信息