Windows Phone开发之集合List和Foreach循环
集合的概念就不说了,原来存放对象比较方便,方便传值。
新建一个Car类:
[csharp] class Car{
public string color {
get;
set;
}
public string name {
get;
set;
}
}
class Car{
public string color {
get;
set;
}
public string name {
get;
set;
}
}
P.S:简单快捷创建Car的属性(带Get/Set方法):
输入prop,Tab后,自动生成 public int MyProperty {get;set;} ,继续Tab一下,修改int,在Tab一下修改MyProperty。
------------------------------------------------------
创建List集合:
[csharp] List<Car> myList = new List<Car>() {
new Car(){ color="Red", name="红旗"},
new Car(){ color="Green", name="绿巨人"}
};
List<Car> myList = new List<Car>() {
new Car(){ color="Red", name="红旗"},
new Car(){ color="Green", name="绿巨人"}
};
该方法也是一种快速,简便的创建方式,占用资源较少,不用新建两个Car对象变量做引用。
普通方法如下:
[csharp] List<Car> myList = new List<Car>();
Car car1=new Car();
car1.color="Red";
car.name="红旗";
Car car2=new Car();
car2.color="Green";
car.name="绿巨人";
mylist.Add(car1);
mylist.Add(car2);
List<Car> myList = new List<Car>();
Car car1=new Car();
car1.color="Red";
car.name="红旗";
Car car2=new Car();
car2.color="Green";
car.name="绿巨人";
mylist.Add(car1);
mylist.Add(car2);
------------------------------------------------
Foreach()循环:
foreach()循环与for()基本相同,只是foreach()专门用来处理集合元素的迭代
[csharp] string mycars = "";
foreach(Car car in myList) {
mycars += car.name + "--" + car.color + Environment.NewLine;
}
mytextblock.Text = mycars;
string mycars = "";
foreach(Car car in myList) {
mycars += car.name + "--" + car.color + Environment.NewLine;
}
mytextblock.Text = mycars;
打印结果:
红旗--Red
绿巨人--Green
摘自 whuarui2010的专栏
补充:移动开发 , Windows Phone ,