C#中的Javascript对象
本文关键字:对象 Javascript 中的 | 更新日期: 2023-09-27 18:27:26
有没有一种简单的方法可以创建如下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]}
];
在C#中(对于Unity 3d)?
我已经看了List、Dictionary和ArrayList,但所有内容都不一样。。。不灵活且过于复杂。。。
这里的主要目标是有一些灵活的东西,可以从许多其他地方访问,而不需要记住数组索引、变量类型等。可能在C#中无法做到。。。但是,一些相当接近的东西应该就足够了。ArrayList也许。。。?
谢谢。
这个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}}
};
但我不确定这是否会实现你想要的(功能方面)
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])
];
和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} },
};
或者为了获得更多的灵活性,你可以在列表中使用它们,比如:
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} },
};
您能否制作一个具有Name
、Score
、Color
、Attribs
属性的Player
模型(类),并将每个Player
存储在内存中的List<Player>
:中
public class Player
{
public string Name { get; set; }
public int Score { get; set; }
public string Color { get; set; }
public int[] Attribs { get; set; }
}
...
List<Player> myPlayers = new List<Player>();
Player joe = new Player();
joe.Name = "Joe";
joe.Score = 25;
joe.Color = "red";
joe.Attribs = new int[] { 0, 1, 2, 3, 4 };;
myPlayers.Add(joe);
使用System.Linq
,您可以查询特定玩家的List<Player>
例如:
Player player = myPlayers.SingleOrDefault(p => p.Name == "Joe");
额外信用-在尝试使用之前,始终测试玩家是否默认:
if (player != default(Player))
{
// do something with joe
}
语法或多或少匹配的是匿名类型:
var players = new[]{
new {name = "Joe", score = 25, color = "red", attribs = new[]{0,1,2,3,4}},
new {name = "Jenny", score = 1, color = "black", attribs = new []{4,3,2,1,0}}
};
但它与JavaScript(C#中的不可变强类型对象数组与JavaScript中的鸭子类型对象字典)有着非常不同的含义。
您可能想研究使用dynamic
和ExpandoObject,如果它们存在于Unity3d中,那么它们可以支持.Net中的JavaScript等语言。
dynamic person = new System.Dynamic.ExpandoObject();
person.Name = "John Smith";
person.Age = 33;
请注意,C#是强类型语言,最好改变思维方式以匹配该语言。如果您无法摆脱鸭子类型的语言,那么使用JavaScript是一个合理的选择。