可以在 C#/.NET 中创建对象的 ArrayList 吗?

发布于 2024-10-02 02:48:19 字数 475 浏览 0 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白鸥掠海 2024-10-09 02:48:19

您想在列表中存储什么?您将 BatchList 声明为包含 POObject,但随后您尝试添加 item,它是什么类型?如果您要向此列表添加不是 POObject 的内容,则可以将其声明为非通用列表:

List BatchList = new List();

或通用对象列表:

List<object> BatchList = new List<object>();

但我怀疑真正的问题可能是您正在尝试添加您收藏的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:

List BatchList = new List();

or as a generic list of objects:

List<object> BatchList = new List<object>();

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 your item variable?

耀眼的星火 2024-10-09 02:48:19

如果您声明 BatchList 的类型为 List,则意味着 List 只能包含 POObject 类型的对象。这就是类型参数的用途。您不能将字符串、整数或任何其他任意对象添加到此列表,只能添加 POObject(以及 POObject 的后代)。

如果你看一下智能感知,你会发现 Add 的签名是这样的:

void Add(POObject item)

如果你确实想要一个包含任意项目的列表,那么使用 ArrayList,它不是泛型类型并且可以接受任何类型的对象。然而,由于 C# 是一种强类型语言,想要像这样的任意列表通常会产生代码味道。

If you declare that BatchList is of type List<POObject>, then that means the List can only contain objects of type POObject. 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 of POObject).

If you take a look at the intellisense, you will see that Add's signature is this:

void Add(POObject item)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文