Custom attribute on property - Getting type and value of attributed property

后端 未结 4 1829
日久生厌
日久生厌 2020-11-29 04:20

I have the following custom attribute, which can be applied on properties:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class Id         


        
4条回答
  •  囚心锁ツ
    2020-11-29 04:32

    A bit late but here is something I did for enums (could be any object also) and getting the description attribute value using an extension (this could be a generic for any attribute):

    public enum TransactionTypeEnum
    {
        [Description("Text here!")]
        DROP = 1,
    
        [Description("More text here!")]
        PICKUP = 2,
    
        ...
    }
    

    Getting the value:

    var code = TransactionTypeEnum.DROP.ToCode();
    

    Extension supporting all my enums:

    public static string ToCode(this TransactionTypeEnum val)
    {
        return GetCode(val);
    }
    
    public static string ToCode(this DockStatusEnum val)
    {
        return GetCode(val);
    }
    
    public static string ToCode(this TrailerStatusEnum val)
    {
        return GetCode(val);
    }
    
    public static string ToCode(this DockTrailerStatusEnum val)
    {
        return GetCode(val);
    }
    
    public static string ToCode(this EncodingType val)
    {
        return GetCode(val);
    }
    
    private static string GetCode(object val)
    {
        var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
    
        return attributes.Length > 0 ? attributes[0].Description : string.Empty;
    }
    

提交回复
热议问题