具有自动实现的getter的标识属性

时间:2018-01-29 06:33:20

标签: c# properties system.reflection

我希望在具有吸气剂的类上识别auto-implemented properties,而不是其他属性'使用其他状态确定其价值的吸气剂。

例如,参加以下课程:

public class RgbColor {

    public int Red { get; }
    public int Green { get; }
    public int Blue { get; }

    public string Hex => String.Format("#{0:X2}{1:X2}{2:X2}", this.Red, this.Green, this.Blue);
    public bool IsBlack { get { return this.Red == 0 && this.Green == 0 && this.Blue == 0; } }
    public bool IsWhite { get { return this.isWhite; } }

    private bool isWhite;

    public RgbColor(int red, int green, int blue) {
        this.Red = red;
        this.Green = green;
        this.Blue = blue;

        this.isWhite = (this.Red == 255 && this.Green == 255 && this.Blue == 255);
    }
}

有没有办法检测到这一点,在上面的示例中,使用自动实现的属性定义了RedGreenBlue的getter,以及{{{ 1}},HexIsWhite不是?

1 个答案:

答案 0 :(得分:0)

使用反射:

public static bool IsAutoProperty(this PropertyInfo prop)
{
    return prop.DeclaringType.GetFields(BindingFlags.NonPublic |BindingFlags.Instance).
           Any(p => p.Name.Contains("<" + prop.Name + ">"));
}