我刚刚在C#做了一些事情,我想知道如何做这样的事情.
Array[0] =
Array['Value'] = 2344;
Array['LocationX'] = 0;
Array['LocationY'] = 0;
Array[1] =
Array['Value'] = 2312;
Array['LocationX'] = 2;
Array['LocationY'] = 1;
Array[2] =
Array['Value'] = 2334;
Array['LocationX'] = 4;
Array['LocationY'] = 3;
Run Code Online (Sandbox Code Playgroud)
它本身并不重要的数据,就是我知道如何在PHP中执行此操作.但是在C#中,我没有,而且我已经尝试了一些方法,但没有运气.
在PHP中我可以做这样的事情:
$Array[0]->Value = 2344;
$Array[0]->LocationX = 0;
$Array[0]->LocationY = 0;
Run Code Online (Sandbox Code Playgroud)
这些值将添加到数组中.
在C#中,我尝试过这种方式并没有这样做.
有人可以告诉我如何在C#中做到这一点?
谢谢.
好吧,您可以像这样编写一个类的实例数组:
public class DataForArray
{
public int Value { get; set; }
public int LocationX { get; set; }
public int LocationY { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后是这样的:
DataForArray[] array = new DataForArray[10];
array[0] = new DataForArray();
array[0].Value = 2344;
etc...
Run Code Online (Sandbox Code Playgroud)
编写一个类或结构来保存Value,LocationX和LocationY.
struct Foo
{
Foo(value, x, y)
{
Value = value;
LocationX = x;
LocationY = y;
}
Foo() {}
int Value;
int LocationX;
int LocationY;
}
Foo[] f = new []
{
new Foo(1, 2, 3),
new Foo(2, 3, 4)
}
Run Code Online (Sandbox Code Playgroud)
或者以这种方式初始化数组:
Foo[] f = new []
{
new Foo() { Value = 1, LocationX = 2, LocationY = 3 },
new Foo() { Value = 4, LocationX = 5, LocationY = 6 },
}
Run Code Online (Sandbox Code Playgroud)
或者使用数组Dictionary<string, int>
.
Dictionary<string, int>[] array = new []
{
new Dictionary<string, int>() {{ "Value", 1 }, {"LocationX", 2}, {"LocationY", 3 }},
new Dictionary<string, int>() {{ "Value", 4 }, {"LocationX", 5}, {"LocationY", 6 }}
}
Run Code Online (Sandbox Code Playgroud)
只有当它需要是动态的时才推荐使用(意味着:你希望在数组的每个元素中都有不同的值,或者你的键是在字符串中,在编译时不知道.)除非它很难维护.