Read Attribute on property without calling getter?

时间秒杀一切 提交于 2019-12-11 08:55:18

问题


C# 4.0. I have a slow property with an attribute. I want to read this attribute without calling the getter:

[Range(0.0f, 1000.0f)]
public float X
{
    get
    {
        return SlowFunctionX();
    }
}

This is what I have now:

public static T GetRangeMin<T>(T value)
{
    var attribute = value.GetType()
        .GetField(value.ToString())
        .GetCustomAttributes(typeof(RangeAttribute), false)
        .SingleOrDefault() as RangeAttribute;

    return (T)attribute.Minimum;
}

var min = GetRangeMin<double>(X); // Will call the getter of X :(

Q: How can I read this attribute without calling the getter of X?


回答1:


You won't be able to get it like that anyway, because you'll be calling something like GetRangeMin<float>(0.0f), and the float type doesn't have a field called whatever-value-X-has.

If you want to do it in a general and type-safe way, you need to use Expressions:

public static T GetRangeMin<T>(Expression<Func<T>> value)

invoked thus:

var min = GetRangeMin(() => X);

You then need to navigate the expression tree to get the property info

MemberExpression memberExpression = value.Body as MemberExpression;
if (null == memberExpression || memberExpression.Member.MemberType != MemberTypes.Property)
    throw new ArgumentException("Expect a field access", "FieldExpression");
PropertyInfo propInfo = (PropertyInfo)memberExpression.Member;

Now you can GetCustomAttributes on the propInfo. Just as an aside, if you're worried about inheritance, you might need to use Attribute.GetCustomAttributes(propInfo, ...) because propInfo.GetCustomAttributes(...) won't walk the inheritance tree even if you ask it to.




回答2:


To read the attribute on the property just load the attribute directly

var attrib = typeof(TheTypeContainingX)
  .GetProperty("X")
  .GetCustomAttributes(typeof(RangeAttribute), false)
  .Cast<RangeAttribute>()
  .FirstOrDefault();
return attrib.Minimum;


来源:https://stackoverflow.com/questions/15620600/read-attribute-on-property-without-calling-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!