相关疑难解决方法(0)

.NET属性:为什么GetCustomAttributes()每次都会创建一个新的属性实例?

所以我在.NET中使用属性玩了一些,并意识到每次调用Type.GetCustomAttributes()都会创建一个属性的新实例.这是为什么?我认为属性实例基本上是一个single-each-MemberInfo,1个实例绑定到Type,PropertyInfo等...

这是我的测试代码:

using System;

namespace AttribTest
{
[AttributeUsage(AttributeTargets.Class)]
class MyAttribAttribute : Attribute
{
    public string Value { get; set; }

    public MyAttribAttribute()
        : base()
    {
        Console.WriteLine("Created MyAttrib instance");
    }
}

[MyAttrib(Value = "SetOnClass")]
class MyClass
{
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Getting attributes for MyClass.");
        object[] a = typeof(MyClass).GetCustomAttributes(false);
        ((MyAttribAttribute)a[0]).Value = "a1";

        Console.WriteLine("Getting attributes for MyClass.");
        a = typeof(MyClass).GetCustomAttributes(false);
        Console.WriteLine(((MyAttribAttribute)a[0]).Value);

        Console.ReadKey();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

现在,如果要实现属性,我希望输出为:

Created MyAttrib instance
Getting attributes for MyClass.
Getting attributes …
Run Code Online (Sandbox Code Playgroud)

.net performance attributes

11
推荐指数
2
解决办法
5784
查看次数

标签 统计

.net ×1

attributes ×1

performance ×1