Can attributes be added dynamically in C#?

2018-12-31 15:32发布

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

10条回答
深知你不懂我心
2楼-- · 2018-12-31 16:09

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.

查看更多
余生请多指教
3楼-- · 2018-12-31 16:15

Well, just to be different, I found an article that references using Reflection.Emit to do so.

Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.

查看更多
初与友歌
4楼-- · 2018-12-31 16:16

This really depends on what exactly you're trying to accomplish.

The System.ComponentModel.TypeDescriptor stuff can be used to add attributes to types, properties and object instances, and it has the limitation that you have to use it to retrieve those properties as well. If you're writing the code that consumes those attributes, and you can live within those limitations, then I'd definitely suggest it.

As far as I know, the PropertyGrid control and the visual studio design surface are the only things in the BCL that consume the TypeDescriptor stuff. In fact, that's how they do about half the things they really need to do.

查看更多
余生无你
5楼-- · 2018-12-31 16:16

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).

查看更多
梦醉为红颜
6楼-- · 2018-12-31 16:22

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

查看更多
人间绝色
7楼-- · 2018-12-31 16:22

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.

查看更多
登录 后发表回答