简体   繁体   中英

Pasting 1d array into 2d array

I'm trying to paste an array of custom class instances into a 2d array of them in a specific position with this code:

arr.Array.SetValue(stripe, topleft.X, topleft.Y);

…and it gives me a System.InvalidCastException with the message Object cannot be stored in an array of this type.

arr.Array is MyClass[,] , and stripe is MyClass[] .

What am I doing wrong here?

This line of code is a part of a larger method that loads a rectangular piece of map for a 2d platformer. The goal is to load separate stripes of tiles into a 2d array so that they form a rectangle of certain dimensions within the 2d array of tiles of larger dimensions.

Of course, this can be done bit by bit, but isn't there some method that allows to do that?

I propose you use a long 1d array instead of a 2d array. Here is an example:

static void Main(string[] args)
{
    int rows = 100, cols = 100;
    // array has rows in sequence
    // for example:
    //  | a11 a12 a13 |    
    //  | a21 a22 a23 | = [ a11,a12,a13,a21,a22,a23,a31,a32,a33]
    //  | a31 a32 a33 |    
    MyClass[] array=new MyClass[rows*cols];
    // fill it here

    MyClass[] stripe=new MyClass[20];
    // fill it here

    //insert stripe into row=30, column=10
    int i=30, j=10;
    Array.Copy(stripe, 0, array, i*cols+j, stripe.Length);

}

System.InvalidCastException with the message Object cannot be stored in an array of this type.

You would have to mention the index of stripe array, from which you might have to copy the value.

    class MyClass
    {
         public string Name {get;set;}
    }

Usage:

   // Creates and initializes a one-dimensional array.
    MyClass[] stripe = new MyClass[5];

    // Sets the element at index 3.
    stripe.SetValue(new MyClass() { Name = "three" }, 3);


    // Creates and initializes a two-dimensional array.
    MyClass[,] arr = new MyClass[5, 5];

    // Sets the element at index 1,3.
    arr.SetValue(stripe[3], 1, 3);

    Console.WriteLine("[1,3]:   {0}", arr.GetValue(1, 3));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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