我正在阅读MSDN上的"with"表达式,并决定对其中提供的示例代码稍加修改.在创建var copy时,我如何附加标签列表,而不必像我在这里(new List<string> { "A", "B", "C"}
)那样显式写出三个标签?我试过Tags = original.Tags + "C"
,但那当然不行.
using System;
using System.Globalization;
using System.Threading.Tasks;
namespace AsyncBreakfast
{
public class ExampleWithReferenceType
{
public record TaggedNumber(int Number, List<string> Tags)
{
public string PrintTags() => string.Join(", ", Tags);
}
public static void Main()
{
var original = new TaggedNumber(1, new List<string> { "A", "B" });
var copy = original with { Tags = new List<string> { "A", "B", "C"} };
Console.WriteLine($"Tags of {nameof(copy)}: {copy.PrintTags()}");
// output: Tags of copy: A, B, C
original.Tags.Add("C");
Console.WriteLine($"Tags of {nameof(copy)}: {copy.PrintTags()}");
// output: Tags of copy: A, B, C
}
}
}