【问题标题】:Identity properties with auto-implemented getters [duplicate]具有自动实现的 getter 的身份属性 [重复]
【发布时间】:2018-01-29 06:33:19
【问题描述】:

与使用其他状态来确定其值的其他属性的 getter 相比,我希望在具有 getter 的类上识别 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 是使用自动实现的属性定义的,而 HexIsWhite 的 getter、而IsBlack 不是吗?

【问题讨论】:

    标签: c# properties system.reflection


    【解决方案1】:

    使用反射:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多