我的问题如上所述。例如
IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));
但毕竟里面只有一项。我们能不能有一个items.Add(item)方法,比如List<T>?
我的问题如上所述。例如
IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));
但毕竟里面只有一项。我们能不能有一个items.Add(item)方法,比如List<T>?
当前回答
你可以做到的。
//Create IEnumerable
IEnumerable<T> items = new T[]{new T("msg")};
//Convert to list.
List<T> list = items.ToList();
//Add new item to list.
list.add(new T("msg2"));
//Cast list to IEnumerable
items = (IEnumerable<T>)items;
其他回答
很抱歉,我又提了一个老问题,但由于它出现在谷歌搜索结果的第一个列表中,我想有些人会一直登陆这里。
在许多答案中,其中一些非常有价值,并且解释得很好,我想补充一个不同的观点,因为对我来说,问题还没有很好地确定。
你正在声明一个存储数据的变量,你需要它能够通过添加项目来改变吗?所以你不应该把它声明为IEnumerable。
由@NightOwl888提议
对于本例,只需声明IList而不是IEnumerable: IList items = new T[]{new T("msg")};物品。添加(新T(“msg2”));
试图绕过声明的接口限制只表明您做出了错误的选择。 除此之外,所有提议用来实现其他实现中已经存在的东西的方法都应该考虑。 允许您添加项的类和接口已经存在。为什么总是复制别人已经做过的东西?
这种考虑是在接口中抽象变量功能的目标。
TL;DR:在我看来,这些是做你需要的事情的最干净的方法:
// 1st choice : Changing declaration
IList<T> variable = new T[] { };
variable.Add(new T());
// 2nd choice : Changing instantiation, letting the framework taking care of declaration
var variable = new List<T> { };
variable.Add(new T());
当您需要使用变量作为IEnumerable时,您将能够。当你需要将它作为数组使用时,你可以调用'ToArray()',它总是应该这么简单。不需要扩展方法,仅在真正需要时才强制转换,能够在变量上使用LinQ,等等…
停止做奇怪和/或复杂的事情,因为你只是在声明/实例化时犯了一个错误。
也许我说得太迟了,但我希望这对将来的任何人都有帮助。
可以使用insert函数在特定索引处添加项。 列表。插入(0项);
不,IEnumerable不支持向它添加项目。另一种解决方案是
var myList = new List(items);
myList.Add(otherItem);
你是否考虑过使用ICollection<T>或IList<T>接口来代替,它们存在的原因正是你想在IEnumerable<T>上有一个Add方法。
IEnumerable<T>用于“标记”一个类型为…嗯,可枚举的,或者只是一个项的序列,而不必保证真正的底层对象是否支持添加/删除项。还要记住,这些接口实现了IEnumerable<T>,所以你得到了所有的扩展方法,你也得到了IEnumerable<T>。
在.net Core中,有一个方法Enumerable。附加就是这样做的。
该方法的源代码可在GitHub.....上获得实现(比其他答案中的建议更复杂)值得一看:)。