微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 有{}操作符吗?

您可以使用
List<string> sList = new List<string>() { "1","2" };

创建一个新列表并添加2个项目. {“1”,“2”} – 部分仅起作用,因为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.

原文地址:https://www.jb51.cc/csharp/95016.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐