具有 init 块的 Java 匿名内部类的 C# 等效项
在 Java 中,我喜欢使用诸如
List<String> list = new ArrayList<String>() {{add("foo");}};
Is there a way to do this in 1 line in C#, so?
In Java, i like to use constructs such as
List<String> list = new ArrayList<String>() {{add("foo");}};
Is there a way to do this in 1 line in C#, too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这称为集合初始值设定项,它是 C# 3.0 的一部分。
除了列表之外,您还可以初始化更复杂类型的集合,只要它们实现 IEnumerable 并为集合初始值设定项中的每个元素提供适当的 Add 方法即可。 例如,您可以像这样使用
Dictionary
的Add(key, value)
方法:更多详细信息可以参见《C# 深度学习》第 8 章,可以从曼宁的网站免费下载。
This is called a collection initializer and it's part of C# 3.0.
As well as lists, you can initialize collections of more complicated types, so long as they implement IEnumerable and have approprate Add methods for each element in the collection initializer. For example, you can use the
Add(key, value)
method ofDictionary<TKey, TValue>
like this:More details can be found in chapter 8 of C# in Depth, which can be downloaded free from Manning's web site.
我认为你想要的是一个数组初始值设定
项多个项目应该以逗号分隔
I think what you want is an array initializer
Multiple items should be comma-separated
您可以在 .NET 3.5 中设置属性值:
或者初始化数组:
但是,您不能以这种方式调用方法。
You can do it in .NET 3.5 to set property values:
Or to initialize an array:
You can't call methods this way, however.
如果您只需要处理将对象添加到集合中,那么集合初始值设定项工作得很好,但如果您需要执行更多静态初始化,则可以使用称为静态构造函数的东西,其工作方式与 java 中的静态初始值设定项
相同href="http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx" rel="nofollow noreferrer">这的格式很差,但似乎覆盖了它
If you just need to deal with adding objects to a collection, then collection initializers work great, but if you need more static initialization to be performed, you can use something called a static constructor that works the same as a static initializer in java
This has poor formatting but seems to cover it