Can attributes be added dynamically in C#?

后端 未结 10 820
别跟我提以往
别跟我提以往 2020-11-22 14:32

Is it possible to add attributes at runtime or to change the value of an attribute at runtime?

相关标签:
10条回答
  • 2020-11-22 14:41

    You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.

    0 讨论(0)
  • 2020-11-22 14:43

    I don't believe so. Even if I'm wrong, the best you can hope for is adding them to an entire Type, never an instance of a Type.

    0 讨论(0)
  • 2020-11-22 14:49

    No, it's not.

    Attributes are meta-data and stored in binary-form in the compiled assembly (that's also why you can only use simple types in them).

    0 讨论(0)
  • 2020-11-22 14:49

    In Java I used to work around this by using a map and implementing my own take on Key-Value coding.

    http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html

    0 讨论(0)
  • 2020-11-22 14:56

    Why do you need to? Attributes give extra information for reflection, but if you externally know which properties you want you don't need them.

    You could store meta data externally relatively easily in a database or resource file.

    0 讨论(0)
  • 2020-11-22 14:59

    If you need something to be able to added dynamically, c# attributes aren't the way. Look into storing the data in xml. I recently did a project that i started w/ attributes, but eventually moved to serialization w/ xml.

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