Change custom attribute's parameter at runtime

前端 未结 2 2001
暗喜
暗喜 2020-11-27 22:32

I need change attribute\'s parameter during runtime. I simplified my problem to simple example.

Attribute class:

    [AttributeUsage(A         


        
相关标签:
2条回答
  • 2020-11-27 23:15

    You cannot change attributes at runtime. They are embedded into the metadata of the assembly. Your method is changing the internal state of a particular instance; but when you load the attribute again, you are getting a different instance.

    0 讨论(0)
  • 2020-11-27 23:21

    This is not possible with reflection, as (as already noted) the metadata is fixed. It is, however, partly possible with TypeDescriptor, which allows adding and replacing of attributes at runtime, and providing complete alternative models (TypeDescriptionProvider, etc). This approach will not be respected by any code that uses reflection, but any code using TypeDescriptor (most typically, data-binding and other UI code) will notice the changes.

    Note TypeDescriptor only really works with one of each attribute-type per typ/member; multi-instance attributes are not well supported.

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