当一个自定义属性的构造函数运行?自定义、函数、属性

2023-09-02 10:17:44 作者:褐瞳。

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

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.