当属性情况下产生的? [英] When are Attribute instances created?

查看:96
本文介绍了当属性情况下产生的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是在同一时间实例的类的实例的属性与它们所施加?

Are attributes instantiated at the same time as instances of the class to which they are applied?

推荐答案

Type.GetCustomAttributes()被称为属性装载。如果你只是实例化类,甚至得到的类型,属性还没有被加载。

Attributes are loaded when the Type.GetCustomAttributes() is called. If you just instantiate the class or even get the type, the attributes are not yet loaded.

请参阅下面的例子:

class Program
{
    static void Main()
    {
        Console.WriteLine("Calling AttributeLoadTest.TestStatic():");
        AttributeLoadTest.TestStatic();
        Console.WriteLine("Loading class");
        var x = new AttributeLoadTest();
        Console.WriteLine("Loading type..");
        var t = typeof (AttributeLoadTest);
        Console.WriteLine("Calling GetCustomAttributes()");
        var ats = t.GetCustomAttributes(false);
    }
}

[ConsoleTest]
class AttributeLoadTest
{
    public static void TestStatic()
    {

    }
}

[AttributeUsage(AttributeTargets.Class)]
class ConsoleTestAttribute : Attribute
{
    public ConsoleTestAttribute()
    {
        Console.WriteLine("ConsoleTestAttribute Constructor");
    }
}

本打印出来:

调用AttributeLoadTest.TestStatic():

Calling AttributeLoadTest.TestStatic():

加载类

加载类型..

调用GetCustomAttributes()

Calling GetCustomAttributes()

ConsoleTestAttribute构造

ConsoleTestAttribute Constructor

所以调用一个静态方法,实例化类,获取类型,没有实例化的属性。呼叫 GetCustomAttributes()一样。

So calling a static method, instantiating the class, getting the type, does not instantiate the attribute. Calling GetCustomAttributes() does.

这篇关于当属性情况下产生的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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