Getting the JsonPropertyAttribute of a Property

前端 未结 1 1408
北荒
北荒 2021-01-06 21:39

I found a post with a great answer for a problem I have, but I can\'t seem to find a small detail I\'m looking for.

public class myModel
{
   [JsonProperty(P         


        
相关标签:
1条回答
  • 2021-01-06 22:04

    Here's a way of doing it while keeping things strongly typed:

    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;
    }
    

    And call it like this:

    var result = GetPropertyAttribute<myModel>(t => t.SomeString);
    

    You can make this a bit more generic, for example:

    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>();
    }
    

    And now because the attribute is generic, you need to move the PropertyName call outside:

    var attribute = GetPropertyAttribute<myModel, JsonPropertyAttribute>(t => t.SomeString);
    var result = attribute.PropertyName;
    
    0 讨论(0)
提交回复
热议问题