我希望在具有吸气剂的类上识别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);
}
}
有没有办法检测到这一点,在上面的示例中,使用自动实现的属性定义了Red
,Green
和Blue
的getter,以及{{{ 1}},Hex
和IsWhite
不是?
答案 0 :(得分:0)
使用反射:
public static bool IsAutoProperty(this PropertyInfo prop)
{
return prop.DeclaringType.GetFields(BindingFlags.NonPublic |BindingFlags.Instance).
Any(p => p.Name.Contains("<" + prop.Name + ">"));
}