简体   繁体   中英

C# Equivalent of Java anonymous inner classes with init blocks

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?

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 of Dictionary<TKey, TValue> like this:

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 .

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:

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

This has poor formatting but seems to cover it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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