c# - 在 C# 中使用跨多种类型的列表

标签 c#

我正在 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);
            }
        }
    }
}

然后我使用以下方式调用此代码:

var myItem = new MyItem();
var myItems= new List<MyItem>();
myItems.Add(myItem);

var result = new MyCollection(myItems);

这给了我一个编译时错误:

cannot convert from 'System.Collections.Generic.List<MyProject.MyItem>' to 'System.Collections.Generic.List<object>'

我认为一切都源自object 。那么,这不应该起作用吗?

无论哪种方式,我认为泛型会更合适。我尝试使用以下内容:

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

然而,这给了我一个编译时错误:

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

关于c# - 在 C# 中使用跨多种类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487001/

相关文章:

c# - 如何在不重定向的情况下检索 HTML 页面?

c# - c# WinForm 中字符串的长度

c# - MVC 4 后期绑定(bind) DataContext 实体 LINQ 引用

c# - WPF 用户控件可编辑属性

c# - "ResolveAssemblyReference"任务失败并出现 System.BadImageFormatException,但程序集未在任何地方使用!

javascript - 为什么我的正则表达式在 .NET 中有效,但在 Javascript 中无效?

c# - 如何通过一次调用 Save 在 NHibernate 中更新一行并自动插入一个新行?

c# - 为什么两次比较只调用一次方法 Equals?

c# - 具有多个数据成员的 IEnumerable

c# - 在将 Html 转换为 Pdf 时显示 Unicode 字符