【发布时间】: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
这对我来说似乎不正确。我做错了什么?
【问题讨论】:
-
为什么要在构造函数中调用 Items.Clear ?这不仅是多余的,它还会抛出 NullReferenceException。
标签: c#