How to determine the attached type from within a custom attribute?

牧云@^-^@ 提交于 2019-12-01 18:17:59

First off, you might consider the existing [DisplayName] for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type into the attribute - i.e.

[Foo("Some name", typeof(Bar)]

What exactly is it you want to do? There may be other options...

Note that for i18n, resx, etc; you can subclass DisplayNameAttribute and provide lookup from keys by overriding the DisplayName getter.

To elaborat. A attribute, built in or custom, is just meta data for a class, or class member, and the attribute itself nas no notation that it's being associated with something.

  • The type knows of it's own metadata
  • The meta data (in this case, the attribute) does not know to whom it belongs
bruno conde

From your sentence "I just want to set a friendly name using reflection" I think you want to set the "MyFriendlyNameForThisClass" name to the attribute at runtime. if so, I don't think that's possible. Please see this thread.

It is clumsy but you could iterate over all classes in the assembly, testing each for the custom attribute that "is" this instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!