且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将对象添加到 arraylist 并读取它们

更新时间:2023-12-05 22:18:46

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.