简体   繁体   English

有{}运营商吗?

[英]Is there a {} Operator?

You can use 您可以使用

List<string> sList = new List<string>() { "1", "2" };

to create a new List and add 2 items. 创建一个新列表并添加2个项目。 The { "1", "2" } -part only works because List<T> has implemented a Add() method. { "1", "2" } -part仅起作用,因为List<T>已实现Add()方法。

my question: is {} something like a operator and can it be overloaded eg to add items twice 我的问题:是{}类似于操作符,可以重载,例如两次添加项目

is {} something like a operator and can it be overloaded eg to add items twice 是{}类似于操作符,可以重载,例如两次添加项目

Any collection type which provides an Add method, built in or as an extension method ( starting from C#-6 ), can use the collection initializer provided by the { } syntax. 任何提供Add方法,内置或作为扩展方法的集合类型( 从C#-6开始 )都可以使用{ }语法提供的集合初始值设定项。 If your Add method adds the same item twice to that collection, then that is what it will do. 如果您的Add方法将相同的项目两次添加到该集合,那么它就是这样做的。

If you'd want the behavior of { } to change, you'd have to override or overload the Add method on the collection. 如果您希望更改{ }的行为,则必须覆盖或重载集合上的Add方法。

Some additional specification goodness (taken from this answer ): 一些额外的规范优点(取自这个答案 ):

C# Language Specification - 7.5.10.3 Collection Initializers C#语言规范 - 7.5.10.3集合初始化器

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. 应用集合初始值设定项的集合对象必须是实现System.Collections.IEnumerable的类型,否则会发生编译时错误。 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. 对于按顺序的每个指定元素,集合初始值设定项在目标对象上调用Add方法,并将元素初始值设定项的表达式列表作为参数列表,为每次调用应用正常的重载决策。 Thus, the collection object must contain an applicable Add method for each element initializer. 因此,集合对象必须包含每个元素初始值设定项的适用Add方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM