你可以使用
List<string> sList = new List<string>() { "1", "2" };
创建一个新列表并添加 2 个项目。 { "1", "2" }
-part 仅适用于 List<T>
实现了 Add()
方法。
我的问题是:{}
像运算符之类的东西,它可以重载吗?添加项目两次
最佳答案
is {} something like a operator and can it be overloaded e.g. to add items twice
任何提供 Add
方法的集合类型,内置或作为扩展方法 ( starting from C#-6 ),都可以使用 { }
语法提供的集合初始值设定项.如果您的 Add
方法将同一项目两次添加到该集合,那么它将执行此操作。
如果您想要更改 { }
的行为,您必须覆盖或重载集合上的 Add
方法。
一些额外的规范优点(取自 this answer ):
C# Language Specification - 7.5.10.3 Collection Initializers
The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer.
关于c# - 有 {} 运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761222/