use*_*335 16 javascript c# unity-game-engine
有没有一种简单的方法来创建类似以下JS代码:
var players = [
{name:"Joe",score:25,color:"red",attribs:[0,1,2,3,4]},
{name:"Jenny",score:1,color:"black",attribs:[4,3,2,1,0]}
];
Run Code Online (Sandbox Code Playgroud)
在C#(Unity 3d)?
我已经查看了List,Dictionary和ArrayList,但是所有内容都是如此......不灵活且过于复杂......
这里的主要目标是有一些灵活的东西,可以从许多其他地方访问,而不需要记住数组索引,变量类型等.可能无法在C#中完成...但是相当接近的东西应该是足够.ArrayList可能......?
谢谢.
OJa*_*Jay 16
这个JavaScript是一个对象数组,可以直接转移到C#,你有多种方法可以使用它和多个集合类来使用(不像只有一个集合类的JavaScript)
它几乎可以在C#中逐字编写,并且完全有效(使用匿名类型):
var players = new [] {
new {name = "Joe",score = 25, color = "red", attribs = new int[]{ 0,1,2,3,4}},
new {name = "Jenny",score = 1, color = "black", attribs = new int[]{4,3,2,1,0}}
};
Run Code Online (Sandbox Code Playgroud)
但我不确定这是否会实现你想要的(功能明智)
IMO创建一个类型化的对象是一种更好的方法(我认为这是C#和JavaScript中更好的方法),所以我会更像这样(JavaScript):
function Player(name,score,color,attribs)
{
this.name = name;
this.score = score;
this.color = color;
this.attribs = attribs;
}
var players = [
new Player("Joe", 25, "red", [0, 1, 2, 3, 4]),
new Player("Jenny",1,"black", [4, 3, 2, 1, 0])
];
Run Code Online (Sandbox Code Playgroud)
在C#中也是如此:
public class Player
{
public string name;
public int score;
public string color;
public int[] attribs;
}
Player[] players = new Player[]{
new Player(){ name = "Joe", score = 25, color = "red", attribs = new int[]{0,1,2,3,4} },
new Player(){ name = "Jenny", score = 1, color = "black", attribs = new int[]{4,3,2,1,0} },
};
Run Code Online (Sandbox Code Playgroud)
或者为了获得更大的灵活性,您可以在List中使用它们,例如:
List<Player> players = new List<Player>(){
new Player(){ name = "Joe", score = 25, color = "red", attribs = new int[]{0,1,2,3,4} },
new Player(){ name = "Jenny", score = 1, color = "black", attribs = new int[]{4,3,2,1,0} },
};
Run Code Online (Sandbox Code Playgroud)