Can I set a fixed ArrayList array in C #, like in C ++?

I have ArrayListone that contains a fixed type of objects. However, every time I need to extract an object for a specific index, I need to give it the type of my type specified by the user from the type of the object.

Is there a way in C # to declare ArrayListfixed types like Java and C ++, or is there any work to avoid type casting every time?

Edit:

I apologize, I forgot to mention that I need the data structure to be thread safe , which is Listnot. Otherwise, I would just use regular Array. But I want to save myself from the efforts of clearly blocking and unlocking when writing an array.

So I thought about using it ArrayList, synchronizing it, but this requires typing every time.

+3
source share
7 answers

You can use List. The List class uses generics to create a strongly typed collection.

To use, just call the new list <Type you want to use> () as follows:

List<string> myStringList = new List<string>();

MSDN has a short article on how you can create thread-safe collections .

+6
source

Take a look at System.Collections.Generic.List

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

+4
source

SynchronizedCollection <T> ? - List <T> .

, System.ServiceModel, ​​ WCF. , System.Collections.Generic. , . LINQ, , . SyncRoot , LINQ:

var syncList = new SynchronizedCollection<int>();
// ...
lock(syncList.SyncRoot)
{
    var itemsInRange = syncList.Where(v => v > 100 && v < 1000);
}

, ( ), . .NET 4.0, System.Collections.Concurrent , ConcurrentBag <T> .

+3

, Generics. List System.Collections.Generics.

+1

FTW!

var items = new List<someType>();
+1

, , , ConcurrentBag<T> :

, .

Note. This requires .NET 4.

0
source

Use System.Collections.Generic.List<T>. If you want thread safety, just block the property SyncRootin your work.

Some codes:

List<string> list = new List<string>();

lock (list.SyncRoot) {
   list.Add("Hello World");
}

If you find that locking is annoying every time, you can override the List class and provide synchronized access to member functions.

0
source

Source: https://habr.com/ru/post/1734988/


All Articles