所以我在.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)