这个问题在这里已经有了答案:
Difference between a List's Add and Append method?
(2 个回答)
去年关闭。
我正在使用 C# System.Collections.Generic List 并且 Add 函数按预期工作但 Append 什么也不做?为什么是这样?我觉得我遗漏了一些明显的东西,但我看不到什么,我使用它与 Add 一样,但它不起作用?
List<string> x = new List<string>();
x.Add("hello");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Add("hi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("oi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("aye");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
输出:
hello
hello
hi
hello
hi
hello
hi
最佳答案
Append返回更新后的集合,而不是修改原始集合。
正确的用法类似于 var y = x.Append("foo")
.请注意,您不能存储 Append
的结果。回到 x
,因为它返回类型为 IEnumerable<string>
的引用而不是 List<string>
.
一般来说,我会坚持使用 List<string>.Add(string)
, 除非您实际上是在处理 IEnumerable<T>
目的。
关于C# 列表添加有效但不追加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022245/