下面这个程序包含了一部分C#3.0的新特征:
1 using System; 2 3 using System.Collections.Generic; 4 5 using System.Text; 6 7 using System.Threading; 8 9 10 11 namespace CSharp3 12 13 { 14 15 class Program 16 17 { 18 19 static void Main(string[] args) 20 21 { 22 23 //扩展方法 24 25 string s = "aa2ss"; 26 27 s.ExMethod(); 28 29 30 31 //对象初始化器 32 33 //对象初始化器的出现,减少了冗余代码 34 35 //直接在实例化类的同时就初始化了字段,但是这跟构造函数是不同的 36 37 myPoint my = new myPoint { X = 0, Y = 1 }; 38 39 Console.WriteLine("X of my =" + my.X.ToString()); 40 41 Console.ReadKey(); 42 43 44 45 //匿名类型 46 47 //编译器会根据属性来推断相应的类型 48 49 //有var的地方就有推断 50 51 Console.Clear(); 52 53 var p1 = new { X = 32, Y = 45 }; 54 55 Console.WriteLine( 56 57"p1 is :{0},and p1.X={1}" , 58 59p1.GetType().ToString(),p1.X); 60 61 Console.ReadKey(); 62 63 64 65 //Lambda表达式 66 67 Console.Clear(); 68 69 LambdaClass.testLambda1(); 70 71 Console.WriteLine("********************"); 72 73 LambdaClass.testLambda2(); 74 75 Console.ReadKey(); 76 77 } 78 79 80 81 } 82 83 84 85 /**//// <summary> 86 87 /// 扩展方法 88 89 /// </summary> 90 91 public static class Extensions 92 93 { 94 95 /**//// <summary> 96 97 /// 扩展方法实际上提供了一种给已定义类添加或者追加方法的方便途径 98 99 /// 这里this关键字是个标示符,this后面的类型定义了要给哪个类追加方法100101 /// </summary>102103 /// <param name="s"></param>104105 public static void ExMethod(this string s)106107 { 108109 Console.WriteLine("This is a Extension Method!!");110111 Console.ReadKey();112113 Console.Clear();114115 }116117 }118119 120121 /**//// <summary>122123 /// 对象初始化器例子124125 /// </summary>126127 public class myPoint128129 { 130131 int x, y;132133 134135 public int Y136137 { 138139 get { return y; }140141 set { y = value; }142143 }144145 public int X146147 { 148149 get { return x; }150151 set { x = value; }152153 }154155 }156157 158159 # region Lambda Expressions160161 162163 public delegate int myDelegate(int a,int b);164165 166167 /**//// <summary>168169 /// Lambda表达式本身是一个委托类型170171 /// </summary>172173 public class LambdaClass174175 { 176177 public static void myMethod(myDelegate myDele)178179 { 180181 Console.WriteLine(182183"Let's have a see what was represented by the delegate:\n{0}",184185 myDele.Method.ToString());186187 Console.WriteLine("the result of culculating between 8 & 8 is :");188189 Console.WriteLine(myDele.Invoke(8, 8));190191 }192193 194195 /**//// <summary>196197 /// 甚至无须声明参数类型,因为编译器会在匹配的委托里找到它们的类型198199 /// </summary>200201 public static void testLambda1()202203 { 204205 LambdaClass.myMethod((x,y) =>x*y);206207 }208209 210211 /**//// <summary>212213 /// 很自然的方式,可以替代匿名方法,或者作为一个匿名的委托214215 /// </summary>216217 public static void testLambda2()218219 { 220221 Thread t = new Thread(() =>222223 { 224225 Console.WriteLine("This is a Lambda Expression!");226227 });228229 t.Start(); 230231 }232233 }234235 #endregion236237} 238 239
的确写得比较爽,体现了“以人文本”的思想. 编译器似乎是程序员的一个朋友,为程序员分担了很多工作,编译器会经常猜到程序员写的是什么,当然前提是你写的程序为编译器的推断提供了充分合理的理由。我想这也是一个趋势吧,让程序员coding时更惬意,更自然,更像”人”一样开发,而不是处处要迎合机器的思维.恩,也许不久以后CSharp会像word一样普及的,期待中...