C# 在C中跨多个类型使用列表

C# 在C中跨多个类型使用列表,c#,C#,我正在C应用程序中开发一个实用程序类。要么我生锈了,要么是配置不正确。我想要一个类,它接受任何类型对象的列表。为了做到这一点,我写了以下内容: using System; using System.Collections.Generic; namespace MyProject { public class ItemCollection { public List<object> Items { get; set; } public

我正在C应用程序中开发一个实用程序类。要么我生锈了,要么是配置不正确。我想要一个类,它接受任何类型对象的列表。为了做到这一点,我写了以下内容:

using System;
using System.Collections.Generic;

namespace MyProject
{
    public class ItemCollection
    {
        public List<object> Items { get; set; }

        public ItemCollection(List<Object> items)
        {
            Items.Clear();
            foreach (Object item in items)
            {
              Items.Add(item);
            }
        }
    }
}
public List<T> Items{ get; set; }
然而,这给了我一个编译时错误,它说:

cannot convert from 'System.Collections.Generic.List<MyProject.MyItem>' to 'System.Collections.Generic.List<object>'
The type or namespace name 'T' could not be found

这对我来说似乎不正确。我做错了什么?

您需要在整个类中添加一个类型参数:

public class ItemCollection<T>
{
    public List<T> Items { get; set; }

    public ItemCollection(List<T> items)
    {
        Items.Clear();
        foreach (T item in items)
        {
          Items.Add(item);
        }
    }
}
另一方面,您可以将构造函数简化为

Items = new List<T>(items);

为什么要调用项。是否在构造函数中清除?它不仅是冗余的,还将抛出NullReferenceException.related
Items = new List<T>(items);