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

前端 未结 10 1863
情话喂你
情话喂你 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条回答
  • 2020-12-28 14:35

    You have to declare your array with the datatype object:

    object[] myArray = { };
    
    myArray[0] = false;
    myArray[1] = 1;
    myArray[2] = "test";
    
    0 讨论(0)
  • 2020-12-28 14:36

    Here is how you can do it

    Use List<object> (as everything is derived from object in C#):

    var list = new List<object>();
    list.Add(123);
    list.Add("Hello World");
    

    Also dynamic might work for you (and your python background)

    var list = new List<dynamic>();
    list.Add(123);
    list.Add(new
    {
        Name = "Lorem Ipsum"
    });
    

    If you wan't to use dynamic you really need to know what you're doing. Please read this MSDN article before you start.

    But do you need it?

    C# is a strongly-typed and very solid programming language. It is very flexible and great for building apps using object-oriented and functional paradigms. What you want to do may be acceptable for python, but looks pretty bad on C#. My recommendation is: use object oriented programming and try to build model for your problem. Never mix types together like you tried. One list is for a single data-type. Would you like to describe your problem in depth so that we can suggest you a better solution?

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

    Very simple—create an array of Object class and assign anything to the array.

    Object[] ArrayOfObjects = new Object[] {1,"3"}
    
    0 讨论(0)
  • 2020-12-28 14:39

    you can use an object array. strings, int, bool, and classes are all considered objects, but do realize that each object doesn't preserve what it once was, so you need to know that an object is actually a string, or a certain class. Then you can just cast the object into that class/data type.

    Example:

    List<object> stuff = new List<object>();
    
    stuff.add("test");
    stuff.add(35);
    
    Console.WriteLine((string)stuff[0]);
    Console.WriteLine((int)stuff[1]);
    

    Though, C# is a strongly typed language, so I would recommend you embrace the language's differences. Maybe you should look at how you can refactor your engine to use strong typing, or look into other means to share the different classes, etc. I personally love the way C# does this, saves me a lot of time from having to worry about data types, etc. because C# will throw any casting (changing one data type to another) errors I have in my code before runtime.

    Also, encase you didn't know, xna is C#'s game framework (didn't have it as a tag, so I assume you aren't using it).

    0 讨论(0)
提交回复
热议问题