将对象添加到arraylist并读取它们 [英] Add objects to arraylist and read them

查看:121
本文介绍了将对象添加到arraylist并读取它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照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 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中将数据类型指定为 JakubDą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<DataPerLabel>存储数据,从而避免强制转换.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆