How to get metadata custom attributes?

后端 未结 5 506
南方客
南方客 2021-01-05 08:23

I have a class that defines data annotations at class level. The meta data class has custom attributes associated with it, along with the usual DisplayName,

5条回答
  •  攒了一身酷
    2021-01-05 08:46

    I offer the following solution as an alternative. It works with any custom attribute (this example demonstrates StringLength) and it's fast. It's based on this method and this method above.

    The MetaDataType attribute and type class:

    [MetadataType(typeof(ImportSetMetaData))]
    public partial class ImportSet
    {
    }
    
    public class ImportSetMetaData
    {
        [StringLength(maximumLength: 32)]
        public string Segment { get; set; }
    

    The extension methods:

    public static class Extension
    {
        private static int? GetMaxLength(Expression> propertyExpression)
        {
            int? result = GetPropertyAttributeValue
                    (propertyExpression, attr => attr.MaximumLength);
            return result;
        }   
    
        public static int? GetMaxLength(this T instance, Expression> propertyExpression)
        {
            return GetMaxLength(propertyExpression);
        }
    
        private static TValue GetPropertyAttributeValue
            (Expression> propertyExpression, Func valueSelector) where TAttribute : Attribute
        {
            var expression = (MemberExpression)propertyExpression.Body;
            string mName = expression.Member.Name;
            Type type = typeof(T);
            MemberInfo member = type.GetMember(mName).FirstOrDefault();
            var attr = member.GetCustomAttribute(inherit: true);
            if (attr != null)
            {
                return valueSelector(attr);
            }
            else
            {
                var mdTypeAttr = (MetadataTypeAttribute)type.GetCustomAttribute(inherit: true);
                type = mdTypeAttr.MetadataClassType;
                member = type.GetMember(mName).FirstOrDefault();
                attr = member.GetCustomAttribute(inherit: true);
                return (attr == null ? default(TValue) : valueSelector(attr));
            }
        }
    }
    

    The usage:

    int n = ImportSet.GetMaxLength(x => x.Segment);
    

提交回复
热议问题