可以在 C#/.NET 中创建对象的 ArrayList 吗?
我正在尝试在 C# 中创建对象的 ArrayList。到目前为止我尝试过的是:
class POObject
{
public List<string> staticCustInfo;
public List<List<string>> itemCollection;
public int testInt;
}
POObject myObject = new POObject();
List<POObject> BatchList = new List<POObject>();
这很好,除非我尝试使用以下方法将对象添加到此列表中:
BatchList.Add(item);
它给了我错误,说它找不到相应的方法来添加到列表中。有什么想法吗?感谢您的帮助。
I'm trying to create an ArrayList of objects in C#. What I've tried so far is:
class POObject
{
public List<string> staticCustInfo;
public List<List<string>> itemCollection;
public int testInt;
}
POObject myObject = new POObject();
List<POObject> BatchList = new List<POObject>();
This is fine, except when I try to add an object to this list using:
BatchList.Add(item);
It gives me errors saying it can't find a corresponding method to add to the list. Any ideas? Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想在列表中存储什么?您将 BatchList 声明为包含 POObject,但随后您尝试添加
item
,它是什么类型?如果您要向此列表添加不是 POObject 的内容,则可以将其声明为非通用列表:或通用对象列表:
但我怀疑真正的问题可能是您正在尝试添加您收藏的
item
类型错误。您能否向我们展示如何获取item
变量?What are you trying to store in your list? You declare a BatchList as containing POObjects, but then you're trying to add
item
, which is of what type? If you're adding things to this list that are not POObjects, you can declare it as either a non-generic list:or as a generic list of objects:
But I suspect the real problem may be that you're trying to add the wrong type of
item
to your collection. Can you show us how you get youritem
variable?如果您声明 BatchList 的类型为
List
,则意味着 List 只能包含POObject
类型的对象。这就是类型参数的用途。您不能将字符串、整数或任何其他任意对象添加到此列表,只能添加 POObject(以及POObject
的后代)。如果你看一下智能感知,你会发现 Add 的签名是这样的:
如果你确实想要一个包含任意项目的列表,那么使用 ArrayList,它不是泛型类型并且可以接受任何类型的对象。然而,由于 C# 是一种强类型语言,想要像这样的任意列表通常会产生代码味道。
If you declare that BatchList is of type
List<POObject>
, then that means the List can only contain objects of typePOObject
. That's what the type parameter is for. You cannot add strings, ints, or any other arbitrary objects to this list, only POObjects (and descendents ofPOObject
).If you take a look at the intellisense, you will see that Add's signature is this:
If you really want a list that contains arbitrary items, then use an
ArrayList
, which is not a generic type and can accept any type of object. However since C# is such a strongly typed language, wanting arbitrary lists like this is usually a code smell.