How to add different types of objects in a single array in C#?

前端 未结 10 1862
情话喂你
情话喂你 2020-12-28 14:17

I am planning to rewrite my Python Tile Engine in C#. It uses a list of all the game objects and renders them on the screen. My problem is that unlike in Python where you ca

相关标签:
10条回答
  • In c# we use an object[] array to store different types of data in each element location.

      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;
    
    0 讨论(0)
  • 2020-12-28 14:20

    You can use an array of object class and all it possible to add different types of object in array.

    object[] array = new object[3];
    array[0] = 1;
    array[1] = "string";
    array[3] = 183.54;
    
    0 讨论(0)
  • 2020-12-28 14:22

    You can write an abstract base class called GameObject, and make all gameObject Inherit it.

    Edit:

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-28 14:22

    In C# 4 and later you can also use dynamic type.

    dynamic[] inputArray = new dynamic[] { 0, 1, 2, "as", 0.2, 4, "t" };
    

    Official docu

    0 讨论(0)
  • 2020-12-28 14:23

    You can use object[] (an object array), but it would be more flexible to use List<object>. It satisfies your requirement that any kind of object can be added to it, and like an array, it can be accessed through a numeric index.

    The advantage of using a List is you don't need to know how items it will hold when you create it. It can grow and shrink dynamically. Also, it has a richer API for manipulating the items it contains.

    0 讨论(0)
  • 2020-12-28 14:31

    C# has an ArrayList that allows you to mix types within an array, or you can use an object array, object[]:

      var sr = new ArrayList() { 1, 2, "foo", 3.0 };
      var sr2 = new object[] { 1, 2, "foo", 3.0 };
    
    0 讨论(0)
提交回复
热议问题