论坛首页 移动开发技术论坛

WP7学习笔记005---Collections(集合类)的使用

浏览 1661 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-04-21   最后修改:2011-04-21

C#其实跟JAVA基本上一样,无论是语法还是其他的什么,所以在C#中存在的Collections集合类很常见,就像在Android中经常用到ArrayList一样。

 

下面是一个WP7版的小例子,以便今后忘记的时候有个回顾的地方

 

1、首先创建一个项目,然后在手机界面中拖入一个Button,一个TextBlock,这个TextBlock属性设置为wrap(自动换行)

 

2、首先,创建一个名为Car.cs的类,类似于JAVA中的javabean,提供的get,set

注意:这里在类Car中输入prop,然后点击两次Tab,会生成一个自动的代码,此时光标指向数据类型int,然后将其改为string,再次点击两次Tab,修改名字为Make或者Model,根据自己的需要。

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Lession1
{
    public class Car
    {
        public String Make { get; set; }
        public String Model { get; set; }
    }
}

 

 

3、下面是Button对应的C#代码

private void myButton_Click(object sender, RoutedEventArgs e)
        {
            Car car1 = new Car();
            car1.Make = "宝马";
            car1.Model = "X6系列";

            Car car2 = new Car();
            car2.Make = "尼桑";
            car2.Model = "Altima";

            Car car3 = new Car();
            car3.Make = "奥迪";
            car3.Model = "A6";

            List<Car> myList = new List<Car>();
            myList.Add(car1);
            myList.Add(car2);
            myList.Add(car3);

            string myCars = "";
            foreach (Car car in myList)
            {
                myCars += car.Make + "-" + car.Model + Environment.NewLine;
            }
            myTextBlock1.Text = myCars;
        }

 

4、运行



 

 

当然,还有另外两种初始化的写法:

 

写法2:

可以将如下代码

           Car car1 = new Car();
            car1.Make = "宝马";
            car1.Model = "X6系列";

            Car car2 = new Car();
            car2.Make = "尼桑";
            car2.Model = "Altima";

            Car car3 = new Car();
            car3.Make = "奥迪";
            car3.Model = "A6";

 

换成下面的代码

 Car car1 = new Car() { Make = "宝马", Model = "X6系列" };
 Car car2 = new Car() { Make = "尼桑", Model = "Altima" };
 Car car3 = new Car() { Make = "奥迪", Model = "A6" };

 

 

写法3:

将如下代码

            Car car1 = new Car();
            car1.Make = "宝马";
            car1.Model = "X6系列";

            Car car2 = new Car();
            car2.Make = "尼桑";
            car2.Model = "Altima";

            Car car3 = new Car();
            car3.Make = "奥迪";
            car3.Model = "A6";

            List<Car> myList = new List<Car>();
            myList.Add(car1);
            myList.Add(car2);
            myList.Add(car3);

 

换成如下的代码,这样会省去很多的代码量,阅读也更加方便

 List<Car> myList = new List<Car>()
            {
                new Car { Make = "宝马", Model = "X6系列"},
                new Car { Make = "尼桑", Model = "Altima"},
                new Car { Make = "奥迪", Model = "A6"}
            };

 

  • 大小: 4.8 KB
论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics