C# 4.0新加特性

协变和逆变

这个在C#2.0中就已经支持委托的协变和逆变了,C#4.0开始支持针对泛型接口的协变和逆变:

IList<string> strings = new List<string>();

IList<object> objects = strings;

协变和逆变仅针对引用类型。

动态绑定

看例子:

class BaseClass
{
    public void print()
    {
        Console.WriteLine();
    }
}
Object o = new BaseClass();
dynamic a = o;
//这里可以调用print方法,在运行时a会知道自己是个什么类型。 这里的缺点在于编译的时候无法检查方法的合法性,写错的话就会出运行时错误。
a.print();

可选参数,命名参数

private void CreateNewStudent(string name, int studentid = 0, int year = 1)

这样,最后一个参数不给的话默认值就是1,提供这个特性可以免去写一些重载方法的麻烦。

调用方法的时候,可以指定参数的名字来给值,不用按照方法参数的顺序来制定参数值:

CreateNewStudent(year:2, name:"Hima", studentid: 4); //没有按照方法定义的参数顺序
posted @ 2016-08-29 10:41  kylin2016  阅读(129)  评论(0编辑  收藏  举报