简体   繁体   中英

What would be a good replacement for C++ vector in C#?

I'm working on improving my skills in other languages, coming from using c++ as my primary programming language. My current project is hammering down C#.net, as I have heard it is a good in-between language for one who knows both c++ and VB.net.

Typically when working with an unknown number of elements in c++ I would declare my variable as a vector and just go from there. Vectors don't seem to exist in c#, and in my current program I have been using arraylists instead, but I'm starting to wonder if it's a good habit to use arraylists as I read somewhere that it was a carryover from .net 1.0

Long question short- what is the most commonly used listing type for c#?

If you target pre .NET 2.0 versions, use ArrayList

If you target .NET 2.0+ then use generic type List<T>

You may need to find replacements for other C++ standard containers, so here is possible mapping of C++ to .NET 2.0+ similar types or equivalents:

std::vector - List<T>
std::list - LinkedList<T>
std::map - Dictionary<K, V>
std::set - HashSet<T>
std::multimap - Dictionary<K, List<V>>

I would recommend you explore the System.Collections namespace, especially the System.Collections.Generics set of objects. The built-in functionality can be strongly typed across the various Lists, Dictionaries and NameValueCollections to provide you with a wide range of capabilities. They are also extendable so if they don't do EXACTLY what you need, you just extend them and add the new functionality.

That'd be List<T> , I suppose. ArrayList is the non-generic type and—as you correctly observed—a leftover from the .NET 1 times. Starting with .NET 2 you can use Generics and therefore List<T> .

Short answer: List<T> . You can find the docs here .

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