C# - 抛掷属性构造异常 [英] c# - Throwing exceptions from attribute constructor

查看:149
本文介绍了C# - 抛掷属性构造异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 上主题和尝试以下操作:

I found this article on the subject and tried the following:

public class FailerAttr : Attribute {
    public FailerAttr(string s) {
        throw new Exception("I should definitely fail!");
    }
}

和单元测试项目中,我有以下几点:

And in unit test project I have the following:

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class Test {
    [TestMethod]
    public void GoFail() {
        // Make sure attribute will get initialized
        new Failer();
    }

    private class Failer {
        [FailerAttr("")]
        public int Prop { get; set; }
    }
}

当我运行测试,它成功。所以,问题是:

When I run the test, it succeeds. So, the questions are:


  1. 为什么不失败

  2. 是不是真的不好?想法抛出从属性异常?因为我觉得我需要

一些环境信息(以防万一它是有关):

Some environment info (just in case it's relevant):


  • 单元测试都通过了ReSharper的单元测试转轮(R#v8.2.0.2160)

  • Visual Studio中v11.0.61030.0 <运行/ LI>
  • Unit tests are run via ReSharper's unit test runner (R# v8.2.0.2160)
  • Visual studio v11.0.61030.0

推荐答案

由于属性为您提供类定义的一部分在运行时(它也被称为元数据在geekspeak)CLR不,除非你的程序的某些部分要求他们实例化它们。这是有道理的:?何苦花费CPU周期的东西,没有人愿意访问

Since attributes are part of class definition available to you at runtime (it's also called "metadata" in geekspeak) CLR does not instantiate them unless some part of your program asks for them. This makes sense: why bother spending CPU cycles for something that nobody wants to access?

由于此,构造函数的执行将不会发生,除非你要求该属性

Because of this, the execution of the constructor will never happen unless you ask for that attribute.

下面是要求一个属性,它会使你的程序的一种方式失败:

Here is one way to ask for an attribute that would make your program fail:

var attr = Attribute.GetCustomAttribute(typeof(Failer).GetProperty("Prop"), typeof(FailerAttr));

此代码使CLR实例化 FailerAttr ,这会触发例外。

This code makes CLR instantiate the FailerAttr, which triggers the exception.

演示上ideone。

如果你不知道该属性的类型,可以同时检索所有属性与此调用:

If you do not know the type of the attribute, you can retrieve all attributes at once with this call:

var allAttributes = Attribute.GetCustomAttributes(typeof(Failer).GetProperty("Prop"));

这导致异常以及(的演示)。

This causes an exception as well (demo).

这篇关于C# - 抛掷属性构造异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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