【问题标题】:Set property value based on some properties根据某些属性设置属性值
【发布时间】:2022-09-23 16:57:42
【问题描述】:

我想在这些条件下将ButtonDisabled 属性设置为false: 至少一个后缀为_Set1 的属性为真,至少一个后缀为_Set2 的属性为true。当条件不再满足时,将ButtonDisabled 属性设置为true

一个想法如何做到这一点?

public bool CheckBox1_Set1 { get; set; }

public bool CheckBox2_Set1 { get; set; }

public bool CheckBox3_Set1 { get; set; }

public bool CheckBox1_Set2 { get; set; }

public bool CheckBox2_Set2 { get; set; }

public bool CheckBox3_Set2 { get; set; }

public bool ButtonDisabled { get; set; }
  • 你想要_____吗ButtonDisabled\ 的后备字段的值,或者您是否希望 ButtonDisabled 成为当其他属性/成员满足某些条件时返回 false 的计算属性(没有后备字段)?

标签: c# .net


【解决方案1】:

这个?

class Smurf
{
    public Boolean CheckBox1_Set1 { get; set; }
    public Boolean CheckBox2_Set1 { get; set; }
    public Boolean CheckBox3_Set1 { get; set; }

    public Boolean CheckBox1_Set2 { get; set; }
    public Boolean CheckBox2_Set2 { get; set; }
    public Boolean CheckBox3_Set2 { get; set; }

    private Boolean Set1HasAtLeast1True => this.CheckBox1_Set1 || this.CheckBox2_Set1 || this.CheckBox3_Set1;
    private Boolean Set2HasAtLeast1True => this.CheckBox1_Set2 || this.CheckBox2_Set2 || this.CheckBox3_Set2;

    public Boolean ButtonDisabled => !( this.Set1HasAtLeast1True && Set2HasAtLeast1True );
}

例子:

void Main()
{
    Smurf s = new Smurf();
    s.CheckBox1_Set1 = true;
    s.CheckBox2_Set2 = true;
    Console.WriteLine( "Should be false: {0}", s.ButtonDisabled );
    
    s.CheckBox1_Set1 = true;
    s.CheckBox2_Set2 = false;
    Console.WriteLine( "Should be true: {0}", s.ButtonDisabled );
}

截图证明:

【讨论】:

  • 这是一个解决方案,但我认为在观察者身上我一直在寻找复杂性:)
猜你喜欢
  • 2019-07-09
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
相关资源
最近更新 更多