簡體   English   中英

如何從列表中獲取下一個值<string>

[英]How to get next value from List<string>

我對列表字符串有問題。 我將3個值放入myCollection

List<string> myCollection = new List<string>();

myCollection.Add(Encoding.Default.GetString(data));
myCollection.Add(Encoding.Default.GetString(data2));
myCollection.Add(Encoding.Default.GetString(data3));

現在我有3個值:A,B,C

但現在我想阻止包含此值的按鈕:

for (var i = 0; i < myCollection.Count; i++)

{

    if (myCollection.Contains(A))
    {

        this.A.Enabled = false;

    }

    else if (myCollection.Contains(B))
    {

        this.B.Enabled = false;
    }

    else if (myCollection.Contains(C))
    {

        this.C.Enabled = false;
    }
}

在此循環之后,僅第一個button = false。 現在循環完成3次,這個相同的嘗試阻止按鈕A,我的問題是:如何阻止其他按鈕?

現在我進入第一個循環運行:

  this.A.Enabled = false;

2nd this.A.Enabled = false;


3rd this.A.Enabled = false;

但我想要 :

1st :   this.A.Enabled = false;

2nd :   this.B.Enabled = false;

3rd :   this.C.Enabled = false;

您不需要為此的循環。 只需使用簡單的if語句,而不使用else

if (myCollection.Contains("A"))
    this.A.Enabled = false;

if (myCollection.Contains("B"))
    this.B.Enabled = false;

if (myCollection.Contains("C"))
    this.C.Enabled = false;

主要是else情況給您帶來了麻煩。 如果A的條件為true,則B和C的代碼未運行。 這就是else方式。

不知道您到底想達到什么目的,但是這里的問題是您使用了if..else。 如果滿足任何條件,則其余條件將無法解決。

要解決您的問題,只需從您的條件中刪除else關鍵字即可。

另外,使用“包含”時不需要循環。

如果您堅持要執行循環,則必須稍微更改條件,然后可以正確使用else:

      for (int i = 0; i < myCollection.Count; i++)            
      {
        if (myCollection[i] == A)
        {
            this.A.Enabled = false;                   
        }

        else if (myCollection[i] == B)
        {
            this.B.Enabled = false;
        }

        else if (myCollection[i] == C)
        {
            this.C.Enabled = false;
        }
      }

暫無
暫無

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

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