将1d数组粘贴到2d数组中
本文关键字:数组 2d 1d | 更新日期: 2023-09-27 18:15:54
我试图将自定义类实例数组粘贴到它们在特定位置的2d数组中,使用此代码:
arr.Array.SetValue(stripe, topleft.X, topleft.Y);
它给了我一个System.InvalidCastException
,上面写着Object cannot be stored in an array of this type.
arr.Array
为MyClass[,]
, stripe
为MyClass[]
。
我在这里做错了什么?
这行代码是为2d平台游戏加载矩形地图的更大方法的一部分。目标是将单独的条纹瓷砖加载到2d数组中,以便它们在2d数组中形成特定尺寸的矩形。
当然,这可以一点一点地完成,但是没有一些方法允许这样做吗?
我建议您使用长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);
}
系统。InvalidCastException和消息Object不能被存储
您必须提到stripe
数组的index
,您可能必须从中复制值。
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));