使用反射,setter 抛出无法捕获的异常 [英] Using reflection, setter throws exception which can't be caught

查看:44
本文介绍了使用反射,setter 抛出无法捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using reflection to set properties on an object. If any of the setters throw an exception, the exception is not caught by the code that makes the SetValue call. Visual Studio tells me that the exception is uncaught by user code.

例如,假设在下面的示例中,target"变量引用的对象上的 Title 属性设置器抛出 ArgumentException.

For example, imagine in the example below that the Title property setter on the object referenced by the "target" variable throws an ArgumentException.

查看调用堆栈,似乎在下面的代码段和 setter 之间存在非托管代码.

Looking at the call stack, it seems that there is unmanaged code between the snippet below and the setter.

有人可以请(& 谢谢!)解释一下:

Can somebody please (& thank you!) explain:

  • 首先为什么会发生这种情况?
  • 是否有一种简单的方法可以在不重新考虑程序逻辑的情况下修复它?

这是我的代码:

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;}

Here is the code for one of many properties that I want to set like this: public string Title { get { return 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;
        }
    }

推荐答案

任何异常都应该被捕获.

Any exception there should be caught.

见小提琴:https://dotnetfiddle.net/koUv4j

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

This includes errors in the reflection call itself (setting the property to the wrong Type), or having an exception within the property's setter itself (set throws).

这会导致其他错误.可能性:

This leads to something else being wrong. Possibilities:

  • 您已将 IDE 设置为在出现所有异常时暂停
  • 异常没有发生在你认为它发生的地方(比如,在 catch 中,它会重新throw)
  • You've got your IDE set to halt on all exceptions
  • The exception isn't happening where you think it is (like, in the catch, which will rethrow)

如果不是这两个之一,请提供更多信息.

If it's not one of those 2 then please provide more information.

这篇关于使用反射,setter 抛出无法捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆