0

我寻找一种在属性中获取自己的属性的方法。

让我展示我正在搜索的内容

我想使用浮点/双精度值的属性来提供比较容差。

例如

[FieldAttribute(CompareTolerance = 0.001)]
public float SomeProperty
{
    get { return this.someProperty; }
    set
    {
        if (Math.Abs(someProperty- value) > 0.001) // here i would like to use somthing like '> FieldAttribute.CompareTolerance'
        this.someProperty = value;
    }
}

从另一个班级我会使用

PropertyInfo propertyInfo = someobject.GetType().GetProperty("SomeProperty");
if (null != propertyInfo)
{
    Attribute attribute = Attribute.GetCustomAttribute(propertyInfo, typeof (FieldAttribute));
    FieldAttribute fieldAttribute = attribue as FieldAttribute;
    return fieldAttribute.CompareTolerance;
}


...

所以最后我只需要

if(Math.Abs(someProperty - value) < someobject.CompareTolerance("SomeField")) ... values are equal

但是有没有一种方法可以在不使用反射的情况下在属性中获取属性( this.CompareTolerance("SomeField") )

4

1 回答 1

1

除了代码生成之外,没有其他方法可以解决这个问题。您可以考虑使用T4 模板在从属性中提取具有反射的值后,使用所需的 getter/setter 代码(可能需要放置在部分方法中)生成类的部分定义。然后再次编译。

我不确定为什么最近每个人似乎都在避免生成代码。T4 使这在现代版本的 VS 中成为一种乐趣。

于 2013-09-27T08:56:16.023 回答