繁体   English   中英

C#提供控件数组属性

[英]C# Giving control Arrays properties

我的项目需要几个控制数组,但是我的代码正在生成错误。

这是我给出常规控件属性的方式(此代码可以正常工作)

TextBox stamText = new TextBox()  
{ 
    Location = new Point(15, 50), 
    Text = "55", 
    Width = 30, 
    Height = 30
};

这是我尝试执行的代码,但针对的是控件数组

TextBox[] stamText = new TextBox[8]  
{ 
    Location = new Point(15, 50), 
    Text = "55", 
    Width = 30, 
    Height = 30 
};

{}中的每个属性都说“;”后出现错误 是期待。

有谁知道如何解决这个问题(赋予控件数组属性)?

* * *扩展

好的,所以我的程序是一种表格,可以在我们进行桌面角色扮演时跟踪玩家的状态。

所以说我和比尔,吉姆和我在一个房间里

我单击表单上的“添加播放器”按钮,它添加了一个播放器以及与该播放器相关的一系列控件

*AddPlayer Button clicked*
Addplayer()

Public void AddPlayer()
{
*Add a bunch of controls*
 checkbox(i)
 textbox(i)
}
i += 1

现在每个人都被击中了10。所以我去改变每个人的耐力-10

if for i = 0 to players added 
   if checkbox(i) = checked then textbox(i).text = (text - 10)

因此,我需要它们成为数组,以便可以通过for循环一次更改多个人员的统计信息。

您似乎对对象和集合初始化器感到困惑。 您在第一种情况下使用的对象初始化器的工作方式如下:

对象初始化程序使您可以在创建时将值分配给对象的任何可访问字段或属性,而不必显式调用构造函数。

class Cat
{
    // Auto-implemented properties. 
    public int Age { get; set; }
    public string Name { get; set; }
}

Cat cat = new Cat { Age = 10, Name = "Fluffy" };

在第二种情况下使用的集合初始值设定项的工作方式如下:

集合初始化程序可让您在初始化实现IEnumerable的集合类时指定一个或多个元素初始化程序。 元素初始值设定项可以是简单值,表达式或对象初始值设定项。 通过使用集合初始值设定项,您不必在源代码中指定对类的Add方法的多次调用;而是,可以使用默认值。 编译器将添加调用。

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

在抛出错误的示例中,您正在使用集合初始化器创建一个由8个文本框组成的数组,但是您传入了对象初始化器。 您得到有关的错误的原因; 是因为; 用于分隔要添加到集合中的对象。 编译器希望看到在集合中添加了8个文本框,每个文本框之间用;分隔; 这是解决此问题的一种方法:

TextBox[] stamText = new TextBox[8]  
{ 
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 },
    new TextBox() { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 } 
};

正如Ian所说,初始化为非默认值时需要指定每个元素。 您正在做的是,您正在尝试初始化TextBox数组的“位置,文本,宽度和高度”属性,但该数组不具备TextBox那些属性。 如果要使用非默认值“初始化*”一个数组,最好的方法是使用如下所示的for循环:

const int numOfElements = 8;
TextBox[] textBoxArray = new TextBox[numOfElements];

for (int i = 0; i < numOfElements; i++)
{
    textBoxArray[i] = new TextBox()  { Location = new Point(15, 50), Text = "55", Width = 30, Height = 30 };
}

* :这并不是真正的初始化,因为在声明数组时已经使用默认值对其进行了初始化。 我猜这更多的是“填充”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM