How do collections and lists store objects of different types? Is it possible?

How do shared collections and list objects store different types? Is it possible?

Because collections and list are replacement for arraylist

+3
source share
3 answers

The main advantage of shared collections is that you can specify the exact type that you want to keep in the collection, and do not need boxing.

You have several options:

  • You stick to unrelated collections in the namespace System.Collectionsthat take an object as a parameter.
  • You create a general collection of an object of type. This is more or less the same as above, but you can use all the extension methods that exist for IEnumerable<T>.
  • , , , .
+1

, , .

, , a MemoryStream, FileStream , List<Stream>:

List<Stream> streams = new List<Stream>();
streams.Add(new MemoryStream());
streams.Add(new FileStream(...));

List<object>:

List<object> objects = new List<object>();
objects.Add("hello"); // A String
objects.Add(5); // An Int32
objects.Add(new Button());
objects.Add(Guid.NewGuid());

, , .

, , , , . is , as:

string maybeString = objects[0] as string;
if (maybeString != null)
{
    Console.WriteLine("String of length {0}", maybeString.Length);
}
+6

, , ; -, List<object>() , , List<IMyCommonInterface>().

, , , .

, , ?

+1
source

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


All Articles