c#面板数组简化了代码

时间:2017-06-23 07:58:54

标签: c# arrays panel simplify

我想简化这段代码。代码应将所有面板(panel1 - panel10)放入面板阵列

解决方案可以使用for循环,但我不知道如何增加面板名称:

public Form1()
    {
        InitializeComponent();

        Panel[] arr = new Panel[10];

        int i = 0;
        arr[i] = panel1;
        arr[i++] = panel2;
        arr[i++] = panel3;
        arr[i++] = panel4;
        arr[i++] = panel5;
        arr[i++] = panel6;
        arr[i++] = panel7;
        arr[i++] = panel8;
        arr[i++] = panel9;
        arr[i++] = panel10;
    }

6 个答案:

答案 0 :(得分:4)

Panel[] panel = new Panel [] 
{
    panel1,
    panel2,
    panel3,
    ...
    panel10,
};

答案 1 :(得分:3)

如果class TestConfigFile(TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): print global_path_config.get('section1', 'a') 直接在表单上,​​您可以尝试 Linq

panel1..panel10

修改:如果您有 using System.Linq; using System.Text.RegularExpressions; ... public Form1() { InitializeComponent(); // If you want all the panels, remove (comment out) "Where" Panel[] arr = Controls .OfType<Panel>() .Where(panel => Regex.IsMatch(panel.Name, "^panel([0-9]|(10))$")) .ToArray(); } 个面板,则唯一需要更改的是过滤器42

Where

如果您想要使用 public Form1() { InitializeComponent(); Panel[] arr = Controls .OfType<Panel>() .Where(panel => { // Given a panel you have to decide should you add it to array or not var match = Regex.Match(panel.Name, "^panel(?<num>[0-9]+)$"); return match.Success && int.Parse(match.Groups["num"].Value) >= 0 && int.Parse(match.Groups["num"].Value) <= 42; }) .ToArray(); } Name(例如panelNumberpanel2panel17 ...)组织所有面板,您可以简化panel347进入

Where

答案 2 :(得分:2)

使用以下内容创建数组:

public Form1()
    {
        InitializeComponent();
        Panel[] arr = new Panel[]{
        panel1,
        panel2,
        panel3,
        panel4,
        panel5,
        panel6,
        panel7,
        panel8,
        panel9,
        panel10
  };
}

答案 3 :(得分:1)

另一种解决方案是使用反射,如:

Panel[] arr = new Panel[10];
const string PanelName = "panel";
for (int i = 0; i < arr.Length; i++)
{
    FieldInfo pi = GetType().GetField(PanelName + (i + 1),
        BindingFlags.NonPublic | BindingFlags.Instance);
    arr[i] = ((Panel)pi.GetValue(this));
}

请注意,这只是一个例子。如果面板不可用,则此代码将因返回null而崩溃。如果可能,您需要稍微改进一下代码。

答案 4 :(得分:0)

你为什么不试试Linq?假设所有面板都在表格中。

var panelArr = Controls.OfType<Panel>(); //Filtering based on Type
panelArr.Where(p=> Regex.IsMatch(p.Name, "^panel([0-9]|(10))$")) //Filtering based on Panel Name
panelArr.ToArray(); //Fianlly into Array

答案 5 :(得分:0)

您可以设置名称panel.Name = "pnl" + i.ToString();

public Form1()
{
    InitializeComponent();

    Panel[] arr = new Panel[10];

    for (int i = 0; i < arr.Length; i++)
    {
        Panel panel = new Panel();
        panel.Name = "pnl" + i.ToString();
        arr[i] = panel;
    }
}