简体   繁体   English

我可以在 C# 数组中存储不同的类型吗?

[英]Can I store different types in a C# array?

I want to store multiple data type in an array of C# .我想在 C# 数组中存储多种数据类型。 I researched on this and found one answer.我对此进行了研究并找到了一个答案。 For example: to use object type, the code for which goes like this例如:要使用对象类型,其代码如下

object[] array = new object[2];

Is there any other way to achieve this?有没有其他方法可以实现这一目标?

It depends on the data types you plan on storing in the array.这取决于您计划在数组中存储的数据类型。
To store different data types in the same array you must use their common ancestor - object being the ultimate base class in the .Net framework will enable you to store any data type inside this array.要将不同的数据类型存储在同一个数组中,您必须使用它们的共同祖先—— object是 .Net 框架中的最终基类,将使您能够在此数组中存储任何数据类型。

However, if you are planing on storing types that derive from a more specific base class - you can use that base class.但是,如果您打算存储从更具体的基类派生的类型 - 您可以使用该基类。
For instance, if you have an Animal base class which derived classes are Cat , Dog , Tiger , Snake and you want to store all of them in an array, you can use an array of Animal to do that.例如,如果您有一个派生类是CatDogTigerSnakeAnimal基类,并且您想将它们全部存储在一个数组中,您可以使用一个Animal数组来做到这一点。

Please note that this also applies to interfaces.请注意,这也适用于接口。 If you have multiple classes that all are implementing the same interface, you can use an array of that interface.如果您有多个类都实现相同的接口,则可以使用该接口的数组。 For instance: var myArray = new INotifyPropertyChanged[3];例如: var myArray = new INotifyPropertyChanged[3]; and inside that array you can put any class implementing that interface.在该数组中,您可以放置​​任何实现该接口的类。

Instead of Array, you can use ArrayList to store values with multiple data type.您可以使用ArrayList代替 Array 来存储具有多种数据类型的值。

Something like:就像是:

   ArrayList a1 = new ArrayList();  //It contains List of object but we can't perform LINQ operations
   a1.Add(1);
   a1.Add("Example");
   a1.Add(true);

More elegant approach would be use of List<Object>更优雅的方法是使用List<Object>

   List<Object> a1 = new List<Object>();
   a1.Add(1);
   a1.Add("Example");
   a1.Add(true);

More about Array, ArrayList and List更多关于Array、ArrayList 和 List

POC : .net Fiddle POC : .net 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM