C# 5.0 畅想(转)

出处:http://www.cnblogs.com/Health/archive/2011/09/10/2173124.html

最近看了这篇文章:
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 (123)) if (x in 1:5if (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<stringintdouble> ReturnMyTuple() { return "Hello World!"424.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 12: Console.WriteLine("1 or 2"); breakcase 3..9: Console.WriteLine("3 to 9"); breakcase >=10: Console.WriteLine("10 or higher"); breakdefault: ... }


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

C# code
switch (aString) { case "one""two": Console.WriteLine("1 or 2"); breakcase "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 = nullif(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(); varvalue = obj?.Bar?.Something?.DoSomething();


(4) "???" 空对象链判断结合操作符:从顶级对象判断是否为null
  就像 ?(a.B.C) 如果a==null则返回null

C# code
MyClass value = nullint something = value.x.y ??? 0//something is now 0


(5) IfNull 和 IfNotNull 关键字,使得非空短路判断更加紧凑

C# code
// instead of if (a != null && a.SomeProperty != null && a.SomeProperty.SomeField != null). // do this:IfNotNull(a.SomeProperty.SomeField)



5. 更强大的泛型约束
(1) 算法类型的约束?(这个没看懂...难道说是T必须都是数值类型?)

C# code
public T Foo<T>(T blah) where T : number { return blah * blah; }


(2) 枚举类型的约束(目前只支持约束到struct)

C# code
public void DoSomething<T>(T enumwhere T : System.Enum { ... }


(3) 操作符约束,即约束T必须都重载了指定的操作符

C# code
public static int Sum<T>(IEnumerable<T> seq) where T : operator(T=T+T){ .. }


(4) 带参数构造方法约束

C# code
where new(intstring)


(5) 约束可以调用某个静态方法?(这个感觉不靠谱,不如允许接口里定义static方法)

C# code
public T Create<T>() where T : static Create() { return T.Create(); }


(6) 可以约束代理
(7) 可以区别class还是interface

C# code
Derive from T: class Foo<T> : T where T : class Constraint for interfaces: class Foo<T> where T : interface



6. 自动属性的增强
(1) 初始值

C# code
public string Name { getset; } = "some value";


(2) readonly声明:只能在构造方法中初始化

C# code
public int SomeValue { getprivate readonly set; }



7. Dynamic的扩展
(1) 更像javascript,使得不用反射就能获得后期绑定的特性

C# code
Currently, this would take: var obj = new Foo(); object temp = obj .GetType() .GetProperty(aVariable) .GetValue(obj,null); int value = (int)temp .GetType() .GetMethod("Method") .Invoke(temp, null); What we want: dynamic obj = newFoo(); int value = obj[aVariable].Method();


(2) 匿名类的属性是只读的,除非通过反射才能修改
希望能像下面:

C# code
var obj = new dynamic { Foo = 1, Bar = "string" }; obj.Foo = 2; obj.NewProperty = Something(); obj["Bar"= "a new value";



8. 不可变类型
现在只有一个办法封装一个不可变属性(这个不可变还指对属性的公开类成员也不可修改)
比如:使用 ReadOnlyCollection<T> 或者自己包装 ICollection<T> 或者使用 Tuple。
就像 Nullable<T>(?) 一样声明 Immutable<T>(#) 声明属性是不可修改。

C# code
class Foo { public int ID { getset; } public string Name { getset; } } .. private Foo# _member; public Foo# Something { get { return _member; } }


注意:Foo类型的公开成员ID和Name是可以Set的,但Foo#声明时,就不可以对ID,Name进行修改,这是最终目的。

9. 对于递归的嵌套迭代子
更加简洁有效的递归迭代

C# code
public override IEnumerable<int> Foo() { yield return 1yield return 2foreach(var i in base.Foo()) yield i; }//allowing me to write: public override IEnumerable<int> Foo() { yield return 1yield return 2yield foreachbase.Foo(); }


* 这里原文直接用 yield base.Foo(); 后面回复有人指出有歧义,我也觉得用yield foreach好理解

10. 特性的增强
(1) lambda表达式可用于特性的参数
(2) 支持泛型的特性
(3) Make attributes first class citizens by allowing any type of parameter type.
  (T___T 这真没看懂)

C# code
[SomeCoolAttribute(s=>s.Foo)] public string MyProp { getset; }



C# code
11. Enum的扩展


(1) 增加 ToDictionary<Tk,Tv> 和 ToList 扩展方法
(2) 类型化的枚举 (不靠谱,毕竟Enum是ValueType的)

C# code
Enum<String> Options { Option1 = "xxx" Option2 = "yyy" }



12. Property Change Notification
把 INotifyPropertyChanged 接口实现作成语法糖了?

C# code
public Notifyable<int> Foo { getset; }



13. 静态方法
(1) 静态的扩展方法 (目前的扩展方法,作用于对象实例上)
(2) 静态的抽象或者虚方法

14. Exception grouping
允许分组捕获异常避免重复的逻辑处理

C# code
try { } catch (ArgumentOutOfRangeException) catch (ArgumentNullException) { // Catch a ArgumentOutOfRangeException or a ArgumentNullException }



15. CsharpRepl
允许C#编译器使用一个默认的类,入口主方法以及默认的命名空间

C# code
// Instead of: using System; class Program { static void Main(string[] args) { Console.WriteLine(fact(10)); Console.ReadLine(); } static int fact(int n) { if (n == 0return 1else return n * fact(n - 1); } } // Use this:static int fact(int n) { if (n == 0return 1else return n * fact(n - 1); } Console.WriteLine(fact(10)); Console.ReadLine();



16. 事件
使用一个 Fire 关键字来触发事件,Fire关键字的作用是只当事件有订阅者时才真正调用。
 

C# code
// Instead of: // copy ref to delegate for thread safety var evt = this.ApplicationTextUpdated; if (evt != null) evt(thisnew EventArgs<string>(applicationText)); // do this Fire(this.ApplicationTextUpdated(thisnewEventArgs<string>(applicationText));



17. OOP的增强
(1) 鸭子类型
(2) Tuple MustDispose
(3) Binding Contract - 指定源属性和对象属性。(不知道是不是指 ":=:")
(4) Typedef 预定义 (C++有)
(5) methodof/propertyof
(6) Roles -- 或者叫做"traits"而它不是指多重继承
  比如:一个人他可能是“演员”也可能是“爸爸”在不同场景下有不同的角色
(7) make void first class (不懂T_T)
(8) 方法返回匿名类的强类型支持。。。

原文地址:https://www.cnblogs.com/smileberry/p/2805350.html