如何将js中的数组转换为C#中的数组?
这是我从js编写的代码。我想用C#设置相同的东西,但不知道如何。我尝试过使用数组,但是信息应该很容易更新,而不必更改代码的其余部分。如何将js中的数组转换为C#中的数组?
例如,我可以从夏季价格:hotell[0].list[0].price_s.text
有没有办法做到这一点在C#中(视觉工作室),在那里你可以把信息像这样的一个数组?内Liste
var hotell = [];
hotell[0] = {
city: "New York",
liste: [
{name: "Aurora", price_s: 590, price_v: 690},
{name: "Downtown", price_s: 660, price_v: 750},
{name: "City Hall", price_s: 450, price_v: 530},
]
};
创建一个名为Hotel的Model类,它具有两个名为“city”和“liste”的属性。 “清单当然”不过是List<HotelDetails>
类
public class HotelDetails
{
public string name { get; set; }
public int price_s { get; set; }
public int price_v { get; set; }
}
public class Hotel
{
public string city { get; set; }
public List<HotelDetails> liste { get; set; }
}
接下来你需要你的数组转换成JSON对象,使一个AJAX调用您的webmethod(如果asp.net web表单应用程序)或请调用您的控制器动作(如果asp.net MVC应用程序)并将您的json对象作为参数传递。
之后,你可以用你的酒店类
类两种Hotel
和项目将是更好的实现,就像提到@degant。
但是,您可以有一个tuple<string, int, int>
的列表。
var hotel1 = new List<Tuple<string, int, int>>
{
new Tuple<string, int, int>("Aurora", 590, 690),
new Tuple<string, int, int>("Downtown", 660, 750),
new Tuple<string, int, int>("City Hall", 450, 530)
};
然后,您可以存储所有的酒店在字典:
var allhotels = new Dictionary<string, List<Tuple<string, int, int>>>
{
{"Hotel1", storage}
};
或者:
var allhotels = new Dictionary<string, List<Tuple<string, int, int>>>();
allhotels.Add("Hotel1", storage);
但你可以看到它变得复杂起来相当快。
最干净的可能是创建一个代表您的数据的类。
class Hotel { string name; int price_s; price_v;}
然后,你既可以创建一个字典,其中的关键是城市的名称和值是酒店的列表:
Dictionary<string, List<Hotel>> hotels;
或者你可以创建另一个类的:
class HotelsPerCity{ string city; List<Hotel> hotels; }
而只保留HotelsPerCity在一个列表:
List<HotelsPerCity> hotels;
技术上发挥上讲,你可以使用匿名类对于这一点,做类似下面
var hotell = new []{
new {city = "New York",
liste= new[]{
new{name= "Aurora", price_s = 590, price_v = 690},
new {name= "Downtown", price_s = 660, price_v = 750},
new {name= "City Hall", price_s= 450, price_v= 530},
}
}};
Console.WriteLine(hotell[0].liste[1]);
这里的问题是,var
关键字推测出的编译器指定的类。也就是说,匿名类是针对包含字段string name
,int price_s
和int price_v
的类型构建的,也是实际酒店的匿名类。
匿名类意味着短命,并且唯一能够从方法返回对象hotell
的方法是将对象作为一个对象,以致于必须稍后将其转换为匿名类型。因为它是匿名的,所以很难:)。你或许也可以跟动态一起走,但这些都是缓慢的反射基础。
IE:你是强类型语言,最好是声明你的类。
拥有酒店及套房班
class Room {
public string name {get;set;}
public int price_s {get;set;}
public int price_v {get;set;}
}
class Hotel {
public string city {get;set;}
public List<Room> liste {get;set;}
}
,你可以得到相当简单的初始化没有什么不同(但也不能等同于JS):
var hotel = new Hotel[]{
new Hotel{city = "New York",
liste= new List<Room>{
new Room{name= "Aurora", price_s = 590, price_v = 690},
new Room{name= "Downtown", price_s = 660, price_v = 750},
new Room{name= "City Hall", price_s= 450, price_v= 530},
}
}};
这可能与周围的相应类型的传递。请注意,这些属性通常是C#的大写字母。
你必须为'Hotel'和'liste'类定义类,然后初始化它们。 – degant
尝试谷歌类的数组 - 我发现这个链接有很多:http:// www。 functionx.com/csharp/arrays/Lesson03.htm – PaulF