C#语法糖

来源:互联网 发布:维尼夫妇知乎 编辑:程序博客网 时间:2024/04/29 11:21

C#语法糖(Csharp Syntactic sugar)大汇总

首先需要声明的是“语法糖”这个词绝非贬义词,它可以给我带来方便,是一种便捷的写法,编译器会帮我们做转换;而且可以提高开发编码的效率,在性能上也不会带来损失。这让java开发人员羡慕不已,呵呵。

 

1.  经过简化的Property

早些时候我们这样声明Property

view sourceprint?
01private string _myName;
02 
03public string MyName
04 
05{
06 
07    get { return _myName; }
08 
09    set { _myName = value; }
10 
11}

千篇一律的这样声明,没有多大意义,于是C#的设计人员将这个千篇一律的工作交给了编译器帮我们做了,我们现在可以这样声明

view sourceprint?
1public string MyName { get; set; }

当然他不会牺牲灵活性,我们可以单独给get或者set设定访问限制符,例如

view sourceprint?
1public string MyName { get; protected internal set; }

 

2.  经过两次变异的委托写法

在.net 1.1时我们不得不声明方法后才在委托中使用,在.net 2.0之后我们可以使用匿名委托,他不单可以简化写法,还可以在匿名委托中访问范围内的变量;再后来拉姆达表达式来了,写法就更简便了。

view sourceprint?
01class MyClass
02{
03    public delegate void DoSomething(int a);
04 
05    //定义方法委托
06    private void DoIt(int a) {
07        Console.WriteLine(a);
08    }
09 
10    private void HowtoDo(DoSomething doMethod,int a) {
11        doMethod(a);
12    }
13 
14    public static void Main(string[] args) {
15        MyClass mc = new MyClass();
16        //调用定义的方法委托
17        mc.HowtoDo(new DoSomething(mc.DoIt), 10);
18        int x = 10;
19        //使用匿名委托
20        mc.HowtoDo(delegate(int a){
21            Console.WriteLine(a + x);
22        },10);
23 
24        //使用lamda表达式
25        mc.HowtoDo(a=>Console.WriteLine(a+x),10);
26 
27        Console.ReadLine();
28    }
29}

3.  集合类的声明

之前我们声明一个List并给list赋初始值,必须得这么写:

view sourceprint?
1List<string> list = new List<string>();
2list.Add("a一");
3list.Add("b二");
4list.Add("c三");

现在不需要了,直接写就可以了

view sourceprint?
1List<string> list = new List<string> {
2            "def","OK"
3};

 

4.  集合类各个项的操作

我们为了逐个处理集合中的项,需要这么写:

view sourceprint?
1foreach (string item in list)
2{
3     Console.WriteLine(item);
4}

现在不需要了,这样就可以了

view sourceprint?
1list.ForEach(a => Console.WriteLine(a));

代码是不是清爽了很多。

 

5.  using == try finally

为了在使用完毕时释放资源,我们经常要用using,using实质上就是try fiannaly的一个语法糖而已。例如

view sourceprint?
1StreamWriter sw = null;
2try
3{
4    sw = new StreamWriter("d:/abc.txt");
5    sw.WriteLine("test");
6}
7finally {
8    if(sw!= null) sw.Dispose();
9}

上面的代码可以简化为:

view sourceprint?
1using (var sw = new StreamWriter("d:/abc.txt")) {
2    sw.WriteLine("test");
3}

6.  可爱的var

var的意义时不必写声明的类型,编译器会根据后面对var的赋值判断它的类型,var的类型一旦确认就不能再改变,它只能作为局部变量使用,不能用做字段也不能用做参数声明。

例如:

view sourceprint?
1var writer = new StreamWriter(path);
view sourceprint?
1for(var i=0;i<100;i++){}

 

7.  问号的演变

老掉牙的一个问号+冒号

view sourceprint?
1var b = 3;
2var a = b > 9?b.ToString():”0”+b;

新宝宝两个问号 ??,它表示左边的变量如果为null则值为右边的变量,否则就是左边的变量值

view sourceprint?
1string a = null;
2var b = a??””;

 

8.  类型实例化的语法糖

view sourceprint?
1public class Abc
2{
3    public int ID { get; set; }
4 
5    public string Name { get; set; }
6 
7    public string Url { get; set; }
8}

我们没有为上面的类声明构造函数,但是我们可以像下面的形式来实例化它

view sourceprint?
1public static void Main(string[] args) {
2        var abc = new Abc{
3            ID=1,
4            Name="yukaizhao",
5            Url="http://yukaizhao.cnblogs.com/"
6        };
7    }

 

9.  传说中的扩展方法

在c#3.5时引入了扩展方法,我们可以在不修改类源码的情况下给类增加实例方法,这个很有意义。它的实质也是一种语法糖的实现

例如我们给String类扩展一个IsNumber的方法:

view sourceprint?
01public static class StringExt {
02    static private Regex regexNumber = new Regex("//d+");
03    static public bool IsNumber(this string input)
04    {
05        if (string.IsNullOrEmpty(input))
06        {
07            return false;
08        }
09        return regexNumber.IsMatch(input);
10    }
11}

我们可以在String实例上调用这个方法了

view sourceprint?
1var abc = “123”;
2var isNumber = abs.IsNumber();

 

10.使用匿名类

view sourceprint?
1var a = new {
2    ID = 1,Name=”yukaizhao”,BlogUrl=”http://www.cnblogs.com/yukaizhao/”
3};

匿名类在linq to sql或者entity framework中返回查询数据时很好用。

如果大家还有更多的语法糖,欢迎分享。同时希望大家享受语法糖,因为他可以给我们带来方便,请不要对它嗤之以鼻,也没必要对它嗤之以鼻。


请尊重作者的劳动,转载请保留链接 玉开的技术博客