当属性情况下产生的?属性、情况下

由网友(爱我就不要离开我)分享简介:是在同一时间实例的类的实例的属性与它们所施加?Are attributes instantiated at the same time as instances of the class to which they are applied?推荐答案在 Type.GetCustomAttributes()被称为属性...

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

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.

阅读全文

相关推荐

最新文章