开发者

How does Collections and List store objects of different types ? Is it Possible?

开发者 https://www.devze.com 2023-01-28 08:44 出处:网络
How does generic collections and 开发者_如何学PythonList store objects of different types ? Is it Possible?

How does generic collections and 开发者_如何学PythonList store objects of different types ? Is it Possible?

Because collections and List are a replacement for arraylist


If you need to store various types, you need to declare your collection to be of a type that all the other types are compatible with.

So for example, to put both a MemoryStream and a FileStream in a list, you might have a List<Stream>:

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

For more disparate types, you may need to go as far as 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());

Note that in this case, value type values will be boxed - whereas they wouldn't in a list of that specific value type.

To use any type-specific members of elements, you'd need to check that they were the right type and cast them, e.g. with is and a cast, or as:

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


The main advantage of generic collections is that you can specify the exact type you want to store in the collection and don't need boxing.

You have some options here:

  • You stick to the nongeneric collections in the System.Collections namespace which take object as a parameter.
  • You create a generic collection of type object. This is more or less the same as above, but you can use all the extension methods that exist for IEnumerable<T>.
  • You create a generic collection of a common interface, that all types you want to store, implement.


well, you need to make the list store the most common denominator; if you want to store anything, you need a List<object>() or perhaps List<IMyCommonInterface>().

However, in my experience, if you find yourself coding like this, you might want to reconsider your architecture.

Perhaps you could explain the solution you're trying to achieve ?

0

精彩评论

暂无评论...
验证码 换一张
取 消