Reflection - get attribute name and value on property

后端 未结 15 1876
谎友^
谎友^ 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:36

    foreach (var p in model.GetType().GetProperties())
    {
       var valueOfDisplay = 
           p.GetCustomAttributesData()
            .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ? 
                p.GetCustomAttribute().DisplayName : 
                p.Name;
    }
    

    In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.

提交回复
热议问题