本文介绍了C#相当于对Java的ArrayList支持GET,设置和删除某些指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Java程序员,我已经使用了一个Java 的ArrayList 之前,现在我想在C#中类似的东西。一些我需要的选项都在这个Java code:

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

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);

我用C#的ArrayList 的LinkedList ,但他们没有,我需要这些简单的选项。是否有支持访问使用索引对象,插入和某些索引中删除在C#中的另一种选择?

I used C# ArrayList and 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?

推荐答案

使用列表< 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];

在C#中的ArrayList来自pre-通用时代寿。由于C#2.0,我们有泛型集合,列表&LT; T&GT; 是那一个例子。由于对这个答案的评论说,如果你使用一个ArrayList,你放入数组列表中的元素将不得不盒装(以对象,因为那唯一的ArrayList的作为输入)。如果你想以后访问他们,他们将不得不明确地拆箱,就像你在你的问题做了什么。 ( - > 一个String =(字符串)arrayList.get(1);

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); )

使用泛型集合(如列表&LT; T&GT; ),没有拳击了,因为编译器知道使用数据类型列表将包括。在这种情况下,字符串。
你也可以有一个列表&LT; INT&GT; 列表&LT;焦炭&GT; 列表&LT;任何方式&gt; ,你可以对它们使用相同的索引功能

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.

这篇关于C#相当于对Java的ArrayList支持GET,设置和删除某些指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 17:59