::
::
::
::
::
//作者:杨卫国
//时间:2008年2月21日
//说明:C#语法新特型示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace C3


{
class Program

{
//新特性1:简单属性,无需另外多写一个私有字段,比较适合于定义实体类
public class GsunisMan

{
//传统写法,属性必须有一个私有字段
private int age;
public int Age

{
get

{
return age;
}
set

{
age = value;
}
}

//3.5写法,直接定义即可;

public string Name
{ get; set; }

public Int64 ID
{ get; private set; }
}

static void Main(string[] args)

{
//新特性2:隐式类型,隐式类型化本地变量,但必须赋初值,编译器通过初值推导出变量类型
var i = 10; //相当于 int i=10;
var s = "甘肃紫光软件研发部"; //s为String类型;

var arrNums = new int[]
{ 3,6,9 };


//新特性3:初始化数组的简写方式:new[],可以回忆一下1.1、2.0怎么定义?

int[] arrNums2 = new[]
{ 1, 2, 43 };//当然也可以写成:var arrNums2 = new[] { 1, 2, 43 };



/**//**//**////新特性4:匿名类型,在2.0中有个匿名方法,很容易混淆

var book1 = new
{ BookName = "《紫光人2007纪念版》", BookNumber = 150,BookPublisher = "甘肃紫光企划部" };
MessageBox.Show(string.Format("书名:{0},数量:{1},出版:{2}" ,book1.BookName , book1.BookNumber , book1.BookPublisher));


/**//**//**////新特性5:对象构造者(实例化时,构造函数后面跟大括号,可直接初始化对象属性),在1.1、2.0中必须先定义,然后初始化

GsunisMan aMan = new GsunisMan()
{Name = "杨卫国", Age = 100 };
MessageBox.Show(string.Format("编号:{0},姓名:{1},年龄:{2}", aMan.ID,aMan.Name,aMan.Age));


/**//**//**////新特性6:集合构造者特性。允许List<>等自定义集合像数组一样用大括号赋初值,在以前只有数组才可以的

List<int> listNums = new List<int>()
{ 1, 3, 54, 6, 78 };
MessageBox.Show(listNums.Count.ToString());

//新特性7.2,请首先看看下面的新特性7.1;
string str = "123";
bool isNum = str.IsAllNumber();
MessageBox.Show(isNum.ToString());

//新特性8:Linq,作用就不多说了,用法太多,自己找资料看;
//从一个集合中找出所有年龄大于55岁的人;
List<GsunisMan> men=new List<GsunisMan>();

men.Add(new GsunisMan
{Name="刘备",Age=65});

men.Add(new GsunisMan
{ Name = "关羽", Age =60 });

men.Add(new GsunisMan
{ Name = "张飞", Age = 50 });
var man= from m in men where m.Age>55 select m; //使用Linq,前面几行在准备数据,感觉有些像Sql语句,呵呵
MessageBox.Show(man.First<GsunisMan>().Name); //在此仅显示第一个人姓名

//新特性9:Lambda表达式"=>",一个简单的例子,用法太多,自己找资料看;

int[] numbers =
{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1); //找出奇数的个数
MessageBox.Show(oddNumbers.ToString());
}

}
static public class ExpandClass

{
//新特性7.1:扩展方法。可在类的外部扩展已有的类,如下是扩展string类,为String类增加一个IsAllNumber方法
//!!!此特性在.NET 2.0下不可用!!!
public static bool IsAllNumber(this string str)

{
foreach (var ch in str)

{
if (!char.IsNumber(ch))

{
return false;
}
}
return true;
}
}
}

posted on
2009-05-13 10:02
craig
阅读(
575)
评论()
收藏
举报