这里有一种方法可以在保持事物强类型的同时做到这一点:
public static string GetPropertyAttribute<TType>(Expression<Func<TType, object>> property)
{
var memberExpression = property.Body as MemberExpression;
if(memberExpression == null)
throw new ArgumentException("Expression must be a property");
return memberExpression.Member
.GetCustomAttribute<JsonPropertyAttribute>()
.PropertyName;
}
var result = GetPropertyAttribute<myModel>(t => t.SomeString);
您可以使其更通用一些,例如:
public static TAttribute GetPropertyAttribute<TType, TAttribute>(Expression<Func<TType, object>> property)
where TAttribute : Attribute
{
var memberExpression = property.Body as MemberExpression;
if(memberExpression == null)
throw new ArgumentException("Expression must be a property");
return memberExpression.Member
.GetCustomAttribute<TAttribute>();
}
现在因为属性是泛型的,所以需要移动
PropertyName
var attribute = GetPropertyAttribute<myModel, JsonPropertyAttribute>(t => t.SomeString);
var result = attribute.PropertyName;