1. ? – Nullable<T>

 
1 [SerializableAttribute]
2 public struct Nullable<T> where T : struct, new()

C#里像int, bool, double这样的struct和enum类型都不能为null。如果确实想在值域上加上null的话,Nullable就派上用场了。T?是Nullable&ly;T>的语法糖。要将T?转为T可以通过类型转换,或者通过T?的Value属性,当然后者要高雅些。

 
1 // Nullable<int> arg = -1;
2 int? arg = -1;
3 if (arg.HasValue) {
4     // int value = (int)arg;
5     int value = arg.Value;
6 }

 

2. ?? – operator ??

o ?? v可以看作是o == null ? v : o的语法糖。??运算符在左操作数非null时返回左操作数,否则返回右操作数。

 
1 string result = gao();
2 Console.WriteLine(result ?? "<NULL>");

 

3. => – lambda expression

看别人代码的过程中才发现原来C#也有lambda了,也才发现自己真的out了。当然,感觉C#里的lambda并没有带来什么革命性的变化,更像是一个语法糖。毕竟这不是Scale,MS也有F#了。

 
1 Func<double, double, double> hypot = (x, y) => Math.Sqrt(x * x + y * y);
2 Func<double, double, string> gao = (x, y) =>
3     {
4         double z = hypot(x, y);
5         return String.Format("{0} ^ 2 + {1} ^ 2 = {2} ^ 2", x, y, z);
6     };
7 Console.WriteLine(gao(3, 4));

 

4. {} – initializer

collection initializer使得初始化一个List, Dictionary变得简单。

 
1 List<string> list = new List<string>{"watashi", "rejudge"};
2 Dictionary<string, string> dic = new Dictionary<string, string>
3 {
4     {"watashi", "watashi wa watashi"},
5     {"rejudge", "-rejudge -pia2dea4"}
6 };

而object initializer其实就是调用完成构造后执行属性操作的语法糖,它使得代码更加简洁,段落有致。试比较:

 

 
1 Sequence activity = new Sequence()
2 {
3     DisplayName = "Root",
4     Activities =
5     {
6         new If()
7         {
8             Condition = true,
9             Else = new DoWhile()
10             {
11                 Condition = false
12             }
13         },
14         new WriteLine()
15         {
16             DisplayName = "Hello",
17             Text = "Hello, World!"
18         }
19     }
20 };
 
1 Sequence activity2 = new Sequence();
2 activity2.DisplayName = "Root";
3  
4 If if2 = new If();
5 if2.Condition = true;
6 DoWhile doWhile2 = new DoWhile();
7 doWhile2.Condition = false;
8 if2.Else = doWhile2;
9 activity2.Activities.Add(if2);
10  
11 WriteLine writeLine2 = new WriteLine();
12 writeLine2.DisplayName = "Hello";
13 writeLine2.Text = "Hello, World!";
14 activity2.Activities.Add(writeLine2);

 

5. { get; set; } – auto-implemented properties

又是一个方便的语法糖,只要简单的一句

 
1 public string Caption { get; set; }

就可以代替原来的一大段代码。

 
1 private string caption;
2 public string Caption
3 {
4     get
5     {
6         return caption;
7     }
8     set
9     {
10         caption = value;
11     }
12 }

 

6. var –  implicit type

var并不是代表任意类型,毕竟C#是个强类型的语言。var只是个在声明变量时代替实际的类型名的语法糖,只能使用在编译器能根据上下文推出其实际类型的地方。这在类型名称藏在好几层namespace或class里的时候,还有在foreach语句中非常有用。

 
1 foreach (var a in dict)
2 {
3     Console.WriteLine("{0} => {1}", a.Key, a.Value);
4 }
posted on 2014-03-07 12:03  Kein  阅读(689)  评论(0编辑  收藏  举报