[英]Pasting 1d array into 2d array
我正在尝试使用以下代码将自定义类实例的数组粘贴到特定位置的二维数组中:
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);
}
消息Object的System.InvalidCastException无法存储在此类型的数组中。
您将不得不提到stripe
数组的index
,您可能必须从该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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.