【问题标题】:Using a list across multiple types in C# [duplicate]在 C# 中使用跨多种类型的列表 [重复]
【发布时间】:2014-12-15 15:07:42
【问题描述】:

我正在开发 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

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

【问题讨论】:

标签: c#


【解决方案1】:

你需要给你的整个类添加一个类型参数:

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

【讨论】:

    猜你喜欢
    • 2018-10-17
    • 2015-11-06
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多