简体   繁体   English

属性构造函数中的自定义操作

[英]Custom actions in attribute's constructor

I've been curious whether it's possible to get a list of all the classes with my own attribute without explicitly iterating over all types defined in an assembly. 我很好奇,是否有可能获得具有我自己的属性的所有类的列表,而无需显式遍历程序集中定义的所有类型。 The thing I've tried is to make attribute's constructor write all the types into a static field. 我尝试过的事情是使属性的构造函数将所有类型写入静态字段。 For unknown reason the list of the types doesn't contain a single entry. 出于未知原因,类型列表不包含单个条目。 The following code outputs 0 to the console window. 以下代码将0输出到控制台窗口。 Why? 为什么?

[AttributeUsage(AttributeTargets.Class)]
class SmartAttribute : Attribute {
    public static List<Type> Types = new List<Type>();
    public SmartAttribute(Type type) {
        Types.Add(type);
    }
}

[SmartAttribute(typeof(Test))]
class Test {
}

class Program {
    static void Main(string[] args) {
        Console.WriteLine(SmartAttribute.Types.Count());
        foreach (var type in SmartAttribute.Types) {
            Console.WriteLine(type.Name);
        }
    }
}

What you are trying to do is not possible. 您试图做的事是不可能的。 Attributes are meta-data, they are not instantiated at run-time, so your constructor isn't called. 属性是元数据,它们不会在运行时实例化,因此不会调用构造函数。

If you step back and think about why, it makes sense. 如果您退后一步,想一想为什么,那是有道理的。 In order for the code you propose to work, the first thing your the run time would have to do before executing any code, is create instances of all attributes. 为了使您建议的代码起作用,在执行任何代码之前,运行时必须要做的第一件事就是创建所有属性的实例。 Then you'd run into some fun scenarios like: 然后您会遇到一些有趣的场景,例如:

 [AttributeB]
 public class AttributeA : Attribute{}

 [AttributeA]
 public class AttributeB : Attribute {}

Which constructor would go first, when would it know to stop, etc? 哪个构造函数最先出现,何时知道停止等等? It's reasons like this why the .Net architects decided not to execute Attributes constructors. 正是这样的原因,.Net架构师决定不执行Attributes构造函数。

Now, to find all the types that are decorated with your attribute, you will need to iterate through all of the types in your assembly from within your Main method (or any other executing method): 现在,要查找用属性修饰的所有类型,您将需要从Main方法(或任何其他执行方法)中迭代程序集中的所有类型:

 Assembly.GetExecutingAssembly()
     .GetTypes()
     .Where(t => Attribute.IsDefined(t, typeof(SmartAttribute)))

See get all types in assembly with custom attribute for more discussion on retrieving types decorated with attributes. 请参阅获取具有自定义属性的程序集中的所有类型,以获取有关获取装饰有属性的类型的更多讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM