Reflection - get attribute name and value on property

后端 未结 15 2079
谎友^
谎友^ 2020-11-22 04:59

I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.

public class Book
{
    [Author(\"         


        
15条回答
  •  执笔经年
    2020-11-22 05:30

    While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.

    If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:

    var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());
    

    This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName". If you had multiple Attributes above answers would get a cast exception.

提交回复
热议问题