将1d数组粘贴到2d数组中

时间:2013-05-30 02:14:00

标签: c# arrays multidimensional-array

我正在尝试使用以下代码将一组自定义类实例粘贴到特定位置的二维数组中:

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

...它为我提供了System.InvalidCastException消息Object cannot be stored in an array of this type.

arr.ArrayMyClass[,]stripeMyClass[]

我在这里做错了什么?

这行代码是一个更大的方法的一部分,它为2d平台加载一个矩形的地图。目标是将单独的瓷砖条纹加载到二维数组中,以便它们在较大尺寸的二维瓷砖阵列中形成一定尺寸的矩形。

当然,这可以一点一点地完成,但是有没有一些方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

我建议您使用长1d数组而不是2d数组。这是一个例子:

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

}

答案 1 :(得分:0)

  

无法存储带有消息Object的System.InvalidCastException   在这种类型的数组中。

您必须提及index stripe数组,您可能需要从中复制该值。

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

用法:

   // 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));
相关问题