想当年学C#的时候.Net还是2.0,学了就直接丢掉了,要不是到MS来实习,估计也未必会再捡起来了,结果.Net都4.0了。最近coding才发现C# 3.0多了好多新特性,而自己还把一些C# 2.0的特性彻底忘了,真不敢说自己会C#了。于是总结一下最近遇到并且常用到的特性吧。
1. ? – Nullable<T>
[SerializableAttribute] 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属性,当然后者要高雅些。
// Nullable<int> arg = -1; int? arg = -1; if (arg.HasValue) { // int value = (int)arg; int value = arg.Value; }
2. ?? – operator ??
o ?? v可以看作是o == null ? v : o的语法糖。??运算符在左操作数非null时返回左操作数,否则返回右操作数。
string result = gao(); Console.WriteLine(result ?? "<NULL>");
3. => – lambda expression
看别人代码的过程中才发现原来C#也有lambda了,也才发现自己真的out了。当然,感觉C#里的lambda并没有带来什么革命性的变化,更像是一个语法糖。毕竟这不是Scale,MS也有F#了。
Func<double, double, double> hypot = (x, y) => Math.Sqrt(x * x + y * y); Func<double, double, string> gao = (x, y) => { double z = hypot(x, y); return String.Format("{0} ^ 2 + {1} ^ 2 = {2} ^ 2", x, y, z); }; Console.WriteLine(gao(3, 4));
4. {} – initializer
collection initializer使得初始化一个List, Dictionary变得简单。
List<string> list = new List<string>{"watashi", "rejudge"}; Dictionary<string, string> dic = new Dictionary<string, string> { {"watashi", "watashi wa watashi"}, {"rejudge", "-rejudge -pia2dea4"} };
而object initializer其实就是调用完成构造后执行属性操作的语法糖,它使得代码更加简洁,段落有致。试比较:
Sequence activity = new Sequence() { DisplayName = "Root", Activities = { new If() { Condition = true, Else = new DoWhile() { Condition = false } }, new WriteLine() { DisplayName = "Hello", Text = "Hello, World!" } } };
Sequence activity2 = new Sequence(); activity2.DisplayName = "Root"; If if2 = new If(); if2.Condition = true; DoWhile doWhile2 = new DoWhile(); doWhile2.Condition = false; if2.Else = doWhile2; activity2.Activities.Add(if2); WriteLine writeLine2 = new WriteLine(); writeLine2.DisplayName = "Hello"; writeLine2.Text = "Hello, World!"; activity2.Activities.Add(writeLine2);
5. { get; set; } – auto-implemented properties
又是一个方便的语法糖,只要简单的一句
public string Caption { get; set; }
就可以代替原来的一大段代码。
private string caption; public string Caption { get { return caption; } set { caption = value; } }
6. var – implicit type
var并不是代表任意类型,毕竟C#是个强类型的语言。var只是个在声明变量时代替实际的类型名的语法糖,只能使用在编译器能根据上下文推出其实际类型的地方。这在类型名称藏在好几层namespace或class里的时候,还有在foreach语句中非常有用。
foreach (var a in dict) { Console.WriteLine("{0} => {1}", a.Key, a.Value); }
haha,谢谢总结,需要快速干活,不想看厚厚的书飘过
哇,
ym all…
做不了正太赚不到米找不到妹子干不了苦力的默默飘过…
啊!无所不能的水寒mm!
tym…
表示都知道不过一半都没用过……
学长不用知道也能赚米……
555 还不会赚米 ….
555 同不会……
学长不用赚米也能做正太……
555 不会做正太……
学长不用做正太也能去 MS……
学长不做正太也有妹子
我到MS做苦力没有妹子要