c# - 为什么抛出 System.Reflection.TargetInvocationException 而不是 System.UriFormatException?
问题描述
我有一个带有 1 个属性和验证的简单类。我希望System.UriFormatException
被抛出,但System.Reflection.TargetInvocationException
被抛出无效的 uri。
public class MyClass
{
private string _baseUrl;
public string BaseUrl
{
get => _baseUrl;
set
{
if (!Uri.IsWellFormedUriString(value, UriKind.Absolute))
{
throw new UriFormatException($"Host is not valid Uri: {BaseUrl}");
}
_baseUrl = value;
}
}
}
如果我改变这个类,使它看起来像下面这样,我调用Validate()
我创建的对象,然后我System.UriFormatException
抛出了,为什么会有这种差异。理想情况下,我想抛出System.UriFormatException
第一个片段。我有一种感觉,是因为在对象实例化过程中被抛出,但想了解更多。
public class MyClass {
public string BaseUrl { get; set; }
public void Validate () {
if (!Uri.IsWellFormedUriString (BaseUrl, UriKind.Absolute)) {
throw new UriFormatException ($"Host is not valid Uri: {BaseUrl}");
}
}
}
我正在更改代码,以便在对象实例化期间引发异常,而不是稍后使用Validate()
. Validate()
这让我可以节省几行,以及可能忘记被调用的事实。另外,我知道ValidationAttribute
类,我对它不感兴趣。
解决方案
推荐阅读
- reactjs - 如果 React 中的变量发生变化,如何重新渲染组件(使用 Hooks)
- python - Pandas to_csv() 创建看起来很奇怪的表
- spring-boot - 在 Spring Boot 中从 LDAP 获取用户组
- email - 如果我更改 DNS MX 记录,我会丢失存储在 Webmail 中的现有电子邮件吗?
- flutter - Flutter - 如何获取拖动对象相对于小部件的位置
- python - 使用乘法和减法加密和解密图像
- spring-boot - 如何编写查询spring boot
- python - 每两列绘制一次
- python - 用 Python 更新数据库。Mysql 可以忽略 ' 内容中的样式标记吗?
- python - 如何获取 json 列表的最后一个元素?