Add objects to arraylist and read them

2019-08-11 14:46发布

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;
    }
}

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));
};

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!

2条回答
Bombasti
2楼-- · 2019-08-11 15:15

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();
}

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();
}

A better approach would be to use generic list/collection List<DataPerLabel> to store the data so that the casting can be avoided.

查看更多
\"骚年 ilove
3楼-- · 2019-08-11 15:24

Yiu should use a List<T> instead of ArrayList. This way every item in your list has the right type already and you can access the members:

foreach (DataPerLabel item in allData)
{
    item.GetLabelItem();
}

This assumes allData is defined like this:

allData = new List<DataPerLabel>();

instead of allData = new ArrayList()

If you really have to use an ArrayList than you should cast your item to the actual type. The code above actually does this allready. However you could also use this:

foreach (var item in allData)
{
    ((DataPerLabel)item).GetLabelItem();
}
查看更多
登录 后发表回答