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

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

问题描述

当它运行?它是否运行,而我使用它,或者只是一次每个对象?它可以做任何事情,或者其行动受到限制?

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天全站免登陆