日期:2014-05-20  浏览次数:20725 次

【有稽之谈】C# 5.0 这个可以有
最近看了这篇文章:
C# 5.0 - not quite there yet!
老外大胆的YY了一下,感觉挺有意思转发过来。
回顾C#发展的历史,C#1.0模仿了Java,并保留了C/C++的一些特性如struct,新学者很容易上手;
C#2.0加入了泛型,匿名方法,yield关键字(为啥VB.NET到现在还没有yield?);
C#3.0加入了一堆语法糖,lambda,linq的加入,让C#变得更加优雅和灵活;
C#4.0增加了动态语言的特性,另外加入的TPL(并行开发库),PLinq等降低现存并发模型的复杂性也是相当的给力。
C#5.0???? 还会有什么奇思妙想?

1. in 和 between 操作符
C# code
if (x in (1, 2, 3)) 
if (x in 1:5)
if (x between(1,5))

- 学python的,更加简洁自然的表达式。

2. 数据结构的增强
(1) 一些BCL(base class library)的Collection类型都变成泛型集合
  比如:ControlCollection, XmlAttributeCollection, SqlErrorCollection, StringCollection
  变成:Collection<Control>, Collection<XmlAttribute>,Collection<SqlError> 等
  这使得遍历这种集合的时候,可以直接用 foreach(var x in ...) 目前虽然实现了迭代,但需要类型声明
(2) Tuple类型的自动装箱,拆箱——看上去就像返回多值一样。
 
C# code
   
 public Tuple<string, int, double> ReturnMyTuple() 
 { 
    return "Hello World!", 42, 4.2; 
 } 
 
 // elsewhere: item1 is a string, item2 is an int, item3 is a double.  
 var item1, item2, item3 = ReturnMyTuple(); 
 

(3) yield foreach (详见后面的嵌套迭代子)

3. switch 语法增强
(1) 智能推测case表达式:比如当switch变量是integer时,允许list,range,甚至是表达式
C# code

 switch (anInt) 
 { 
        case 1, 2:  
            Console.WriteLine("1 or 2"); 
            break; 
        case 3..9: 
            Console.WriteLine("3 to 9"); 
            break; 
        case >= 10: 
            Console.WriteLine("10 or higher"); 
            break; 
        default: 
            ... 
 } 


(2) 支持更多的类型,同时支持case中使用list
 
C# code

 switch (aString) 
 { 
        case "one", "two": 
            Console.WriteLine("1 or 2"); 
            break; 
        case "three": 
            Console.WriteLine("3"); 
            break; 
        default: 
            ... 
 } 

(3) 允许在switch语句块中,省略对象访问成员(类似VB.NET的With...End With)
C# code
 
    switch (aString) 
    { 
        case .IsNullOrEmpty(): 
            ... 
        case .Length > 100: 
            ... 
        case .Contains("foo"): 
            ... 
     } 



4. Null 安全
(1) 不可为空操作符
C# code

Void DoX(MyClass! obj) { … }
// The following would make the compiler say: 
// "Cannot convert string to string!, an explicit conversion exists
string! nonNullable = someFunctionThatReturnsAString();

(2) 返回值不可为空的代理,并支持编译检查
C# code
DelegateType! DelegateVar;

(3) "?."类成员Null安全的操作符: 你可以省掉大量的非空判断
C# code

// Instead of doing:
var obj = Foo(); 
Bar value = null; 
if(obj.Bar != null && obj.Bar.Something != null) 
{ 
  value = obj.Bar.Something.DoSomething(); 
} 
//You can do this with Groovy's null safe member operator ?.
var obj = Foo(); 
var value = obj?.Bar?.Something?.DoSomething(); 


(4) "???" 空对象链判断结合操作符:从顶级对象判断是否为null