我正在尝试使用以下代码将一组自定义类实例粘贴到特定位置的二维数组中:
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 平台游戏加载矩形 map 的更大方法的一部分。目标是将单独的瓷砖条纹加载到二维数组中,以便它们在更大尺寸的二维瓷砖阵列中形成特定尺寸的矩形。
当然,这可以一点一点地完成,但是没有一些方法可以做到这一点吗?
最佳答案
我建议您使用长一维数组而不是二维数组。这是一个例子:
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);
}
关于c# - 将一维数组粘贴到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826893/