簡體   English   中英

如何在C#中執行此操作?

[英]How to do this in c#?

我有一個MyClass列表,在主頁上有10個控件,這些控件將顯示有關該項目列表的信息。 我想要的是檢查列表中項目的數量,然后使多余的控件不可見。 現在,我正在使用此代碼,但是有更簡單的方法嗎?

 if (myList.Count > 0)
 {
      Control1.MyClassInfo = myList[0];
      if (myList.Count > 1)
      {
           Control2.MyClassInfo = myList[1];
           if (myList.Count > 2)
           {
                // and like that till 10
           }
           else
           {
                Control3.Visible = false;
                Control4.Visible = false;
                // till 10
           }
       }
       else
       {
           Control2.Visible = false;
           Control3.Visible = false;
           // till 10
       }
  }
  else
  {
       Control1.Visible = false;
       Control2.Visible = false;
       Control3.Visible = false;
       // and then till 10
  }

好吧,只需將您的控件添加到列表中(有序)。

像這樣

var controlList = new List<Control>{ Control1, Control2, Control3 /*etc*/};


var count = myList.Count;
for (var i = 0; i < controlList.Count; i++) {
  controlList[i].Visible = count > i;
}

您可以創建控件列表

List<Control> MyControls = new List<Control>{Control1, Control2,..,Control10};

接着

foreach(var C in MyControls)
    C.Visible=false;

for(int i=0; i<myList.Count; i++)
    C[i].Visible=true;

編輯:對於這里更高級的編碼器,此技術稱為Composite Pattern

基本上就是這樣。 但是您可以通過兩種方式改進該基本概念:

1)使用收藏

List<Control> _controls1to10;

將控件放入該集合中,並編寫如下方法:

private void setVisibility(List<Control> _controls, bool visible)
{
    foreach (Control c in _controls1to10)
    {
        c.Visible = visible;
    }
}

這將使事情變得容易。

2)使用布爾表達式而不是嵌套的if ,如下所示:

bool hasElements = myList.Count > 0;
bool hasMoreThan1 = myList.Count > 1;

// ... and so on

這意味着您將主開關置於頂部,並在以下代碼中使用它們。 這是一個說明概念的幻想示例 ,但不適用於您的代碼:

bool isEditable = User.LoggedIn && SystemState.Maintenance == false && item.Count > 0;

editButton.Visible = isEditable;
dropList.Visible = !isEditable;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM