在不调用getter的情况下读取属性的属性? [英] Read Attribute on property without calling getter?

查看:70
本文介绍了在不调用getter的情况下读取属性的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#4.0。我有一个带有属性的 slow 属性。我想读取此属性而不调用getter:

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

这就是我现在拥有的:

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:我在不调用 X 的吸气剂的情况下读取了此属性?

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

推荐答案

您无论如何都将无法获得它,因为您将调用 GetRangeMin< float>(0.0f)之类的东西,并且float类型没有

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.

如果要以通用且类型安全的方式进行操作,则需要使用Expressions:

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)

这样调用:

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;

现在,您可以在<$ GetCustomAttributes c $ c> propInfo 。顺便说一句,如果您担心继承,则可能需要使用 Attribute.GetCustomAttributes(propInfo,...),因为 propInfo。即使您要求,GetCustomAttributes(...)也不会遍历继承树。

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.

这篇关于在不调用getter的情况下读取属性的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆