支持获取、设置和删除某些索引的 Java arraylist 的 C# 等效项 [英] C# equivalent for java arraylist supporting get, set and remove certain Index

查看:21
本文介绍了支持获取、设置和删除某些索引的 Java arraylist 的 C# 等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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# ArrayListLinkedList,但它们没有我需要的这些简单选项.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?

推荐答案

use 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];

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

使用泛型集合(如List ),不再需要装箱,因为编译器知道列表将包含什么数据类型.在这种情况下,字符串.您还可以拥有 ListListList,并且您可以使用相同的索引功能在他们身上.

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.

这篇关于支持获取、设置和删除某些索引的 Java arraylist 的 C# 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆