【问题标题】:Set property value from another property where List() is used从使用 List() 的另一个属性设置属性值
【发布时间】:2019-10-08 10:45:37
【问题描述】:

如何从另一个使用 List<string>() 的属性设置属性?

如下图,在EnableTest1我要设置bool属性EnableTest2 为假,所以当EnableTest1 为真时它总是返回假。

public class Test
{

   public List<string> _list;
   public Test(List<string> list)
   {
       _list = list;
   }

   public bool EnableTest1 => _list.All(x => x == "Test1");
   public bool EnableTest2 => _list.All(x => x == "Test2");
   public bool EnableTest3 => _list.All(x => x == "Test3"); 
   public bool EnableTest4 => _list.All(x => x == "Test4");
}

【问题讨论】:

  • 所以您希望每个属性都有一个设置器,它基本上会覆盖您在代码中的行为?

标签: c# properties


【解决方案1】:

您只需检查EnableTest1 是否为false

public bool EnableTest2 => !EnableTest1 && _list.All(x => x == "Test2");

现在,如果EnableTest1true,那么EnableTest2 总是false,如果EnableTest2 我们检查_list 项。

代码:

public class Test {

  public List<string> _list;

  public Test(List<string> list) {
    // We should validate public members arguments
    if (null == list)
      throw new ArgumentNullException(nameof(list));

    _list = list;
  }

  public bool EnableTest1 => _list.All(x => x == "Test1");
  public bool EnableTest2 => !EnableTest1 && _list.All(x => x == "Test2");
  public bool EnableTest3 => _list.All(x => x == "Test3");
  public bool EnableTest4 => _list.All(x => x == "Test4");
}

【讨论】:

  • 感谢 Dmitry 这个解决方案帮助我达到了预期的结果:)
【解决方案2】:

你的问题有点不清楚,但这是怎么回事?

public class Test
{

   public List<string> _list;
   public Test(List<string> list)
   {
       _list = list;
   }

   public bool EnableTest1 => _list.All(x => x == "Test1");
   public bool EnableTest2 => EnableTest1 && _list.All(x => x == "Test2");
   public bool EnableTest3 => EnableTest2 && _list.All(x => x == "Test3"); 
   public bool EnableTest4 => EnableTest3 && _list.All(x => x == "Test4");
}

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2017-02-27
    相关资源
    最近更新 更多