l33*_*33t 1 c# custom-attributes
C#4.0.我有一个属性缓慢的属性.我想在不调用getter的情况下读取此属性:
[Range(0.0f, 1000.0f)]
public float X
{
get
{
return SlowFunctionX();
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我现在拥有的:
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 :(
Run Code Online (Sandbox Code Playgroud)
问:如何在不调用getter的情况下读取此属性X?
要读取属性上的属性,只需直接加载属性即可
var attrib = typeof(TheTypeContainingX)
.GetProperty("X")
.GetCustomAttributes(typeof(RangeAttribute), false)
.Cast<RangeAttribute>()
.FirstOrDefault();
return attrib.Minimum;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
302 次 |
| 最近记录: |