简体   繁体   English

一步创建ArrayList

[英]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 . 我极力地尝试使用Visual Studio 2012C#中 一步 创建一个枚举对象之外的ArrayList 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. 但是没有理由再使用旧的ArrayList了。 In this case you could use a List<class1.enum> (apart from the fact that enum is a keyword). 在这种情况下,您可以使用List<class1.enum> (除了enum是关键字的事实)。

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. 除非您有充分的理由使用Arraylist,否则应将数组列表替换为通用列表。 You can find more about using generic list in Benefits of Generics on MSDN 您可以在MSDN上的Generics of Generics中找到有关使用泛型列表的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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