简体   繁体   English

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

[英]How to do this in c#?

I have a List of MyClass and in the main page I have 10 controls which will display the information about that list of Items. 我有一个MyClass列表,在主页上有10个控件,这些控件将显示有关该项目列表的信息。 What I want is to check the count of the items in the List and then make the excess controls invisible. 我想要的是检查列表中项目的数量,然后使多余的控件不可见。 Now I'm using this code but is there an easier way of doing this? 现在,我正在使用此代码,但是有更简单的方法吗?

 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
  }

Well, just add your controls in a list (ordered). 好吧,只需将您的控件添加到列表中(有序)。

Something like that 像这样

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;
}

You could create a list of your controls 您可以创建控件列表

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

and then 接着

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

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

EDIT: for the more advanced coders here, this technique is called the Composite Pattern . 编辑:对于这里更高级的编码器,此技术称为Composite Pattern

Basically, that's it. 基本上就是这样。 But you can improve on that basic concept in two ways: 但是您可以通过两种方式改进该基本概念:

1) use a collection 1)使用收藏

List<Control> _controls1to10;

Put your controls into that collection and write a method like this: 将控件放入该集合中,并编写如下方法:

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

This will make things easier. 这将使事情变得容易。

2) use boolean expressions instead of nested if s, like this: 2)使用布尔表达式而不是嵌套的if ,如下所示:

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

// ... and so on

This means that you have master switches at the top and use them in the following code. 这意味着您将主开关置于顶部,并在以下代码中使用它们。 This is a fantasy example to clear the concept but does not apply to your code: 这是一个说明概念的幻想示例 ,但不适用于您的代码:

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