【问题标题】:I am using too many if statements [duplicate]我使用了太多的 if 语句 [重复]
【发布时间】:2019-03-20 00:07:57
【问题描述】:

我写了一点 C#,但我确信这 17 个 if 语句可以减少。我已经尝试了很多,但到目前为止没有什么对我有用。它是一个 Windows 窗体应用程序,供想知道的人使用。

MySqlCommand cmdcount = new MySqlCommand("Select count(vak_id) from bezet", conn);
        var counter = cmdcount.ExecuteScalar();
        int count = 0;
        count = Convert.ToInt32(counter);

        while(count > 0)
        {
            MySqlCommand cmdklant = new MySqlCommand("Select klant_id from bezet where vak_id = @id", conn);
            cmdklant.Parameters.AddWithValue("@id", count);
            var spotinfo = cmdcount.ExecuteScalar();
            string infospot = Convert.ToString(spotinfo);

            if (infospot == "")
            {
                if (count == 8)
                {
                    P8.BackColor = Color.Green;
                }
                else if(count == 7)
                {
                    P7.BackColor = Color.Green;
                }
                else if (count == 6)
                {
                    P6.BackColor = Color.Green;
                }
                //etc...
            }
            else
            {
                //the same but then color.red
            }
            count--;
        }

【问题讨论】:

  • 这对曾经怀疑它的人来说就像现在一样。
  • 我可能会创建一个 List 并在其中使用索引。如果它不工作,用户界面可能没有时间显示更改。刷新可能会有所帮助..
  • Dictionary<int, Color>

标签: c# mysql object dynamic


【解决方案1】:

因此,您加载一个计数器,然后为每个关联的“P”根据其他条件设置颜色

把那些“P”的东西放到一个数组中怎么样:

int count = ...
new [] { P1, P2, P3, P4 .. P8 }
.Take(count)
.Select((p, idx) => new { P = p, Index = idx})
.ToList()
.ForEach(pIndexPair => 
 {
      var infoSpot = LoadInfoSpot(pIndexPair.Index);
      pIndexPair.P.BackColor = string.IsNullOrEmpty(infospot) ? Color.Green : Color.Red;
 });

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    相关资源
    最近更新 更多