简体   繁体   English

将一维数组粘贴到二维数组中

[英]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. …这给了我一个System.InvalidCastException消息, Object cannot be stored in an array of this type.

arr.Array is MyClass[,] , and stripe is MyClass[] . arr.ArrayMyClass[,] ,而stripeMyClass[]

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. 这行代码是较大的方法的一部分,该方法为2d平台平台加载矩形地图。 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. 目标是将单独的图块条纹加载到2d数组中,以便它们在较大尺寸的2d图块数组中形成一定尺寸的矩形。

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. 我建议您使用长的1d数组而不是2d数组。 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. 消息Object的System.InvalidCastException无法存储在此类型的数组中。

You would have to mention the index of stripe array, from which you might have to copy the value. 您将不得不提到stripe数组的index ,您可能必须从该index复制值。

    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));

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

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