【问题标题】:multidimensional Array position as objectname in c#多维数组位置作为c#中的对象名
【发布时间】:2017-10-22 04:29:53
【问题描述】:

我有一个多维数组,我正在遍历它......它的工作方式就像我想要的那样。 但我想使用位置来更改我创建的面板(Windows 窗体)的文本。示例:我有位置 [0, 9] 并且有一个“M”(字符),现在我想将此 M 写为面板 p009 的文本。 像这样:

if (gameView[j,i] == 'M')
                    {
                        //p + j + 0 + i.Text = 'M';
                    }

【问题讨论】:

  • 那么您的表单中有 90 个面板类型的变量?非常糟糕的主意。为什么不做一个面板类型的多维数组,用p[0,9]代替呢?

标签: c# winforms multidimensional-array


【解决方案1】:

如果您的 Panels 在类级别声明,您可以使用反射来获取它们:

// Get the type handle of a specified class.
Type myType = typeof(Form1);

// Get the fields of the specified class.
FieldInfo[] myField = myType.GetFields();

FieldInfo theRightField = myField
    .Where(f => f.Name.Equals(
        String.Format("p{0}{1:u2}", j, i)
    )).First();

Panel p = (Panel)theRightField.GetValue(this);

但正如 cmets 中提到的,更好的解决方案是声明第二个数组来保存它们:

Panel[,] myPanels = new Panel[10,10];
for (int j = 0; j < 10; j++)
{
    for (int i = 0; i < 10; i++)
    {
        myPanels[j,i] = new Panel();
    }
}

【讨论】:

  • 所以我需要自己编写Form1.Designer.cs文件,对吧? (只是我小组的一部分)
  • @SimonB 不。您永远不会自己更改设计器文件。在调用设计器方法之后,在 Form1 的构造函数中实例化这些面板。
猜你喜欢
  • 2014-01-07
  • 2013-06-27
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多