Reflection - get attribute name and value on property

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

    Just looking for the right place to put this piece of code.

    let's say you have the following property:

    [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
    public int SolarRadiationAvgSensorId { get; set; }
    

    And you want to get the ShortName value. You can do:

    ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;
    

    Or to make it general:

    internal static string GetPropertyAttributeShortName(string propertyName)
    {
        return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;
    }
    

提交回复
热议问题