支持获取、设置和删除某些索引的 Java arraylist 的 C# 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12342637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:30:06  来源:igfitidea点击:

C# equivalent for java arraylist supporting get, set and remove certain Index

c#javacollectionsarraylistlinked-list

提问by sajad

I am a Java programmer, I have used a Java ArrayListbefore and now I want to have something like that in C#. Some of options I need are in this Java code:

我是一名 Java 程序员,我以前使用过 Java ArrayList,现在我想在 C# 中使用类似的东西。我需要的一些选项在此 Java 代码中:

String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
ArrayList arrayList = new ArrayList(35);
arrayList.add(strs[0]);
arrayList.add(strs[1]);
arrayList.remove(0);
arrayList.set(0, strs[2]);
String s = (String) arrayList.get(1);

I used C# ArrayListand LinkedList, but they don't have these simple options that I need. Is there another option in C# supporting accessing objects with indexes, inserting and removing from certain index?

我使用了 C#ArrayListLinkedList,但它们没有我需要的这些简单选项。C# 中是否有另一个选项支持访问带有索引的对象,从某个索引中插入和删除?

回答by Thousand

use List <T>

利用 List <T>

 String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
 List<string> stringList = new List<string>();
 stringList.add(strs[0]);
 stringList.add(strs[1]);
 stringList.RemoveAt(indexYouWantToDelete)     
 String s = stringList[0];

ArrayLists in c# come from the pre-generic era tho. Since C# 2.0 we have generic collections, List <T>being one example of that. As the comment on this answer says, if you use an ArrayList, the elements that you put into the arraylist will have to be boxed (to Object, because thats the only thing an ArrayList takes as input). If you want to access them after that, they will have to be explicitly unboxed, like what you did in your question. ( --> String s = (String) arrayList.get(1);)

c# 中的 ArrayLists 来自前泛型时代。从 C# 2.0 开始,我们就有了泛型集合,这List <T>就是一个例子。正如对此答案的评论所说,如果您使用 ArrayList,则您放入 arraylist 的元素将必须装箱(到Object,因为这是 ArrayList 唯一作为输入的内容)。如果您想在此之后访问它们,则必须明确地将它们拆箱,就像您在问题中所做的那样。( --> String s = (String) arrayList.get(1);)

using generic collections (like List <T>), there is no boxing anymore, as the compiler knows what datatype the list will consist of. In this case, Strings. You could also have a List<int>, List<char>, or List<whatever>, and you can use the same indexing functionality on them.

使用泛型集合(如List <T>),不再有装箱,因为编译器知道列表将包含什么数据类型。在这种情况下,字符串。你也可以有一个List<int>List<char>或者List<whatever>,你可以对它们使用相同的索引功能。

回答by L.B

Use List<T>...........................................

使用List<T>.....................................

which has AddRemove, RemoveAtindexers like list[i]etc.

其中有AddRemoveRemoveAt索引器等list[i]