简体   繁体   中英

Create ArrayList in one step

I'm desperately trying to create an ArrayList out of objects of an enumeration in one step in C# with Visual Studio 2012 . It should look like something of the following:

new ArrayList( {class1.enum.sample1, class1.enum.sample2, class1.enum.sample3} );

When I'm writing it in two lines, it works:

class1.enum[] array = {class1.enum.sample1, class1.enum.sample2, class1.enum.sample3};
ArrayList test = new ArrayList(ha);

But I need to write it in one line. Could you help me, please?

You need another collection like an array to be able to use the collection initializer :

var al = new ArrayList { new[] { class1.enum.sample1, class1.enum.sample2, class1.enum.sample3 } };

But there is no reason to use the old ArrayList anymore. In this case you could use a List<class1.enum> (apart from the fact that enum is a keyword).

You do not need parenthesis () for array list initializer. You can initialize in a single line as under.

ArrayList test = new ArrayList{class1.enum.sample1, class1.enum.sample2, class1.enum.sample3} 

Array list should be replace with generic list unless you have solid reason to use Arraylist. You can find more about using generic list in Benefits of Generics on MSDN

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