加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 有{}操作符吗?

发布时间:2020-12-15 06:41:10 所属栏目:百科 来源:网络整理
导读:您可以使用 Liststring sList = new Liststring() { "1","2" }; 创建一个新列表并添加2个项目. {“1”,“2”} – 部分仅起作用,因为List T实现了Add()方法. 我的问题:{}类似于操作符,可以重载,例如两次添加项目 解决方法 is {} something like a operator a
您可以使用
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读