自定义属性的构造函数何时运行? [英] When is a custom attribute's constructor run?

查看:30
本文介绍了自定义属性的构造函数何时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候运行?它是为我应用它的每个对象运行,还是只运行一次?它可以做什么,或者它的行为受到限制?

When is it run? Does it run for each object to which I apply it, or just once? Can it do anything, or its actions are restricted?

推荐答案

构造函数何时运行?用示例试试:

When is the constructor run? Try it out with a sample:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Creating MyClass instance");
        MyClass mc = new MyClass();
        Console.WriteLine("Setting value in MyClass instance");
        mc.Value = 1;
        Console.WriteLine("Getting attributes for MyClass type");
        object[] attributes = typeof(MyClass).GetCustomAttributes(true);
    }

}

[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    public MyAttribute()
    {
        Console.WriteLine("Running constructor");
    }
}

[MyAttribute]
class MyClass
{
    public int Value { get; set; }
}

输出是什么?

Creating MyClass instance
Setting value in MyClass instance
Getting attributes for MyClass type
Running constructor

因此,当我们开始检查属性时,就会运行属性构造函数.请注意,属性是从类型中获取的,而不是类型的实例.

So, the attribute constructor is run when we start to examine the attribute. Note that the attribute is fetched from the type, not the instance of the type.

这篇关于自定义属性的构造函数何时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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