.NET Attributes: Why does GetCustomAttributes() make a new attribute instance every time?

前端 未结 3 1279
再見小時候
再見小時候 2020-12-04 01:34

So I was playing around a little more with attributes in .NET, and realized that every call to Type.GetCustomAttributes() creates a new instance of my attribute. Why is that

相关标签:
3条回答
  • 2020-12-04 01:58

    Object-creation is cheap.

    If you had an attribute like

    public class MyAttribute : Attribute {
        public virtual string MyText { get; set; }
    }
    

    and applied it to a class like

    [MyAttribute(MyText="some text")]
    public class MyClass {
    }
    

    and you retrieved one like

    var attr =
        typeof(MyClass).GetCustomAttributes(typeof(MyAttribute), false)
        .Cast<MyAttribute>().Single();
    

    and you set some properties on it like

    attr.MyText = "not the text we started with";
    

    what should happen, and what would happen, the next time you called

    Console.WriteLine(
        typeof(MyClass).GetCustomAttributes(typeof(MyAttribute), false)
        .Cast<MyAttribute>().Single().Name
    );
    

    ?

    0 讨论(0)
  • 2020-12-04 02:01

    Attributes aren't stored in memory as objects, they're only stored as metadata in the assembly. When you query for it, it will be constructed and returned, and usually attributes are throwaway objects so for the runtime to keep them around just in case you'd need them again would probably waste a lot of memory.

    In short, you need to find another way to store your shared information.

    Here's the documentation on attributes.

    0 讨论(0)
  • 2020-12-04 02:11

    It's because the attributes are saved in metadata. Attributes should be used for informations such as "user-friendly name of property", etc...

    0 讨论(0)
提交回复
热议问题