I have an ArrayList
which contains fixed type of objects.
However everytime I need to extract an object a particular index, I need to typecast it to my user defined type from object type.
Is there a way in C# to declare ArrayList
of fixed types just like Java and C++, or is there a work around to avoid the typecasting everytime?
Edit:
I apologize I forgot mentioning that I require the datastructure to be thread-safe, which List
is not. Otherwise I would have just used a normal Arr开发者_如何学Cay
. But I want to save myself from the effort of explicitly locking and unlocking while writing the array.
So I thought of using ArrayList
, synchronize it, but it requires typecasting every time.
You could use a List. The List class takes advantage of generics to make a strongly typed collection.
To use, just call new List< Type you want to use >() like this:
List<string> myStringList = new List<string>();
MSDN has a quick article on some ways you can make collections thread safe.
Take a look at System.Collections.Generic.List
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
Have you looked into SynchronizedCollection<T>? It is basically a thread-safe version of List<T>.
Note that this collection is part of System.ServiceModel, as it was added to support the channel dispatchers of WCF. It is a public collection that can be used by any code however, and is in the System.Collections.Generic namespace. All of its methods and its indexer are synchronized, so you would not have to manage locking yourself. Beware of LINQ, however, as the enumerator for this collection is not synchronized. You would need to lock on SyncRoot yourself if you wish to use the enumerator or use LINQ:
var syncList = new SynchronizedCollection<int>();
// ...
lock(syncList.SyncRoot)
{
var itemsInRange = syncList.Where(v => v > 100 && v < 1000);
}
Keep in mind, it uses hard locking (the lock keyword), and with many threads it will not be the most performant solution. If you have the option of using .NET 4.0, I would look into the new System.Collections.Concurrent namespace for some tasty new morsels like ConcurrentBag<T>.
Yes, but you need to use Generics. Look at the List class in the System.Collections.Generics namespace.
Generic Lists FTW!
var items = new List<someType>();
Use System.Collections.Generic.List<T>
. If you want thread safe, simply lock the SyncRoot
property in your operation.
Some code:
List<string> list = new List<string>();
lock (list.SyncRoot) {
list.Add("Hello World");
}
If you find every time to lock is annoying, you can override the List class and provide synchronized access on member functions.
If thread-safety is your concern then perhaps ConcurrentBag<T>
would do the trick:
Represents a thread-safe, unordered collection of objects.
Note: This requires .NET 4.
精彩评论