将对象添加到 arraylist 并读取它们 [英] Add objects to arraylist and read them
问题描述
我正在尝试按照 DataPerLabel
的代码将 DataPerLabel
的对象添加到我的 Arraylist allData
:
I'm trying to add objects of DataPerLabel
to my Arraylist allData
, following the code of DataPerLabel
:
class DataPerLabel
{
public String labelName;
public String labelAdress;
public String dataType;
public DataPerLabel(String labelName, String labelAdress, String dataType)
{
this.labelName = labelName;
this.labelAdress = labelAdress;
this.dataType = dataType;
}
public String getLabelName()
{
return labelName;
}
public String getLabelAdress()
{
return labelAdress;
}
public String getDataType()
{
return dataType;
}
}
在下面的代码中,我尝试将 DataPerLabel
的对象添加到我的 arraylist
:
In the following code I try to add the objects of DataPerLabel
to my arraylist
:
submitButton.Click += (sender, args) =>
{
String label = textboxLabel.Text;
String adress = textboxAdress.Text;
String dataType = "hey";
if (buttonsLabelBool.Checked)
{
dataType = "Bool";
}
else if (buttonsLabelReal.Checked)
{
dataType = "Real";
}
else if (buttonsLabelInt.Checked)
{
dataType = "Int";
}
allData.Add(new DataPerLabel(label, adress, dataType));
};
最后,我尝试通过在 textbox
中显示它来读出 arrayList
,请参阅以下代码:
And finally I try to read out the arrayList
by displaying it in a textbox
, see the following code:
private void test()
{
Button btn = new Button();
btn.Location = new Point(500,500);
btn.Text = "test";
btn.Click += (sender, args) =>
{
foreach (var item in allData)
{
//Display arraylist per object here
//Something like : item.getLabelName();
}
};
}
我不知道我做错了什么,希望你能帮忙!
I'm not sure what I'm doing wrong, hope you can help!
推荐答案
ArrayList
存储System.Object
的列表.您需要将对象强制转换回 DataPerLabel
,如下所示:
ArrayList
stores a list of System.Object
. You need to cast the object back to DataPerLabel
as follows:
foreach (var item in allData)
{
((DataPerLabel)item).getLabelName();
}
或者,您可以在 foreach 中指定数据类型而不是 var
作为 Jakub Dąbek 在评论中指出:
Alternatively, you could specify the data type in the foreach instead of var
as Jakub Dąbek pointed out in the comment as follows:
foreach (DataPerLabel item in allData)
{
item.getLabelName();
}
更好的方法是使用通用列表/集合 List
来存储数据,从而避免强制转换.
A better approach would be to use generic list/collection List<DataPerLabel>
to store the data so that the casting can be avoided.
这篇关于将对象添加到 arraylist 并读取它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!