Get [DisplayName] attribute of a property in strongly-typed way

后端 未结 8 1825
猫巷女王i
猫巷女王i 2020-12-02 08:43

Good day!

I\'ve such method to get [DisplayName] attribute value of a property (which is attached directly or using [MetadataType] attribut

8条回答
  •  难免孤独
    2020-12-02 08:53

    I found another nice code snippet here, and I have slightly modified it for 'DisplayName' purpose

        public static string GetDisplayName(Expression> expression)
        {
            var attribute = Attribute.GetCustomAttribute(((MemberExpression)expression.Body).Member, typeof(DisplayNameAttribute)) as DisplayNameAttribute;
    
            if (attribute == null)
            {
                throw new ArgumentException($"Expression '{expression}' doesn't have DisplayAttribute");
            }
    
            return attribute.DisplayName;
        }
    

    And usages

    GetDisplayName(i => i.PropertyName)
    

提交回复
热议问题