[英]C# Equivalent of Java anonymous inner classes with init blocks
In Java, i like to use constructs such as 在Java中,我喜欢使用诸如的结构
List<String> list = new ArrayList<String>() {{add("foo");}};
Is there a way to do this in 1 line in C#, too? 有没有办法在C#的1行中做到这一点呢?
This is called a collection initializer and it's part of C# 3.0. 这称为集合初始化程序 ,它是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. 除了列表之外,您还可以初始化更复杂类型的集合,只要它们实现IEnumerable并且对集合初始值设定项中的每个元素都有适当的Add方法。 For example, you can use the
Add(key, value)
method of Dictionary<TKey, TValue>
like this: 例如,您可以使用
Dictionary<TKey, TValue>
的Add(key, value)
方法,如下所示:
var dict = new Dictionary<string, int>
{
{"first", 10 },
{"second", 20 }
};
More details can be found in chapter 8 of C# in Depth, which can be downloaded free from Manning's web site . 更多细节可以在C#in Depth的第8章找到,可以从Manning的网站免费下载。
I think what you want is an array initializer 我想你想要的是一个数组初始化器
List<string> list = new List<string>() { "foo" };
Multiple items should be comma-separated 多个项目应以逗号分隔
List<string> list = new List<string>() { "foo","bar","bas"};
You can do it in .NET 3.5 to set property values: 您可以在.NET 3.5中设置属性值:
List<string> list = new List<string> () { Property = Value, Property2 = Value2 };
Or to initialize an array: 或者初始化一个数组:
List<string> list = new List<string> () { "value1", "value2" };
You can't call methods this way, however. 但是,您不能以这种方式调用方法。
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 如果你只需要处理向集合添加对象,那么集合初始化器工作得很好,但是如果你需要执行更多的静态初始化,你可以使用一些静态构造函数,它与java中的静态初始化程序一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.