c# - 有 {} 运算符吗?

标签 c# list

你可以使用

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/

相关文章:

java - 循环遍历列表并根据数据创建 View

Python 2D 列表切片,其中一个列表充满空字符串

ReadKey等待输入两次后的C# Console.ReadLine

c# - 如何在 C# 中访问对象?

python - 即使使用多种过滤方法,为什么在创建列表时仍然有 None 值?

list - 如何获取在 Scala 的列表中多次出现的所有元素的集合?

python - 如何在 Python 中构建一个所有值都是 [] 的独立实例的字典?

c# - 在 VS2005 中获取 C# 变量的确认框的输入

c# - C# 中的 C++ 库 - 继承类

c# - 创建一个有效的数据类型,用于按初始和结果单位 C# 查找转换因子