public abstract class GameObject { public GameObject(); } public class TileStuff : GameObject { public TileStuff() { } } public class MoreTileStuff : GameObject { public MoreTileStuff() { } } public class Game { static void Main(string[] args) { GameObject[] arr = new GameObject[2]; arr[0] = new TileStuff(); arr[1] = new MoreTileStuff(); } }
你可以使用一个object数组。 strings , int , bool和classes都被认为是对象,但确实意识到每个对象都不会保留曾经的对象,所以你需要知道一个对象实际上是一个字符串,或者某个类。 然后,您可以将对象强制转换为该类/数据类型。
var sr = new ArrayList() { 1, 2, "foo", 3.0 }; var sr2 = new object[] { 1, 2, "foo", 3.0 };
在c#中,我们使用object []数组在每个元素位置存储不同类型的数据。
object[] array1 = new object[5]; // // - Put an empty object in the object array. // - Put various object types in the array. // - Put string literal in the array. // - Put an integer constant in the array. // - Put the null literal in the array. // array1[0] = new object(); array1[1] = new StringBuilder("Initialized"); array1[2] = "String literal"; array1[3] = 3; array1[4] = null;