zoukankan      html  css  js  c++  java
  • C# 3.0 的特性 总结

    C# 作为当前版,发布于2007年10月17日,是.NET Framework 3.5 的一部分, 它的新特性灵感来自于函数式编程语言,如:Haskell 和 ML,并广泛地引入了Language Integrated Query (LINQ) 模式到通用语言运行库中e.[4]

     Linq语言集成查询(英语:Language Integrated Query,缩写:LINQ):[5] "from, where, select" context-sensitive keywords allowing queries across SQL, XML, collections, and more. These are treated as keywords in the LINQ context, but their addition won't break existing variables named from, where, or select.

    类型初始化器Customer c = new Customer();
    c.Name = "James";
    可写作:

    Customer c = new Customer { Name="James" };


     集合初始化器MyList list = new MyList();
    list.Add(1);
    list.Add(2);
    可写作

    MyList list = new MyList { 1, 2 };
    假设 MyList 实现了 System.Collections.IEnumerable 且有一个Add 方法method[6]

     匿名类型var x = new { Name="James" };
    局部变量类型推断局部变量 类型推断:

    var x = new Dictionary<string, List<float>>();
    等同于

    Dictionary<string, List<float>> x = new Dictionary<string, List<float>>();
    它只是一个语法糖, 这个特性被匿名类型声明时所需要

    Lambda表达式

    Lambda表达式指:

    listOfFoo.Where(
        delegate(Foo x)
        {
            return x.Size > 10;
        }
    )
    可写作
    listOfFoo.Where(x => x.Size > 10);
    编译器翻译Lambda表达式为强类型委托或强类型表达式树.

     自动化属性编译器将自动生成私有变量和适当的getter(get访问器)和setter(set访问器),如:

    public string Name
    {
        get;
        private set;
    }


    扩展方法

    扩展方法指,一个静态类包含this关键字作为方法的第一参数时,这个方法将被添加到该this的类型中:

    public static class IntExtensions
    {
        public static void PrintPlusOne(this int x)
        {
            Console.WriteLine(x + 1);
        }
    }
     
    int foo = 0;
    foo.PrintPlusOne();


    分部方法Allow codegenerators to generate method declarations as extension points that are only included in the source code compilation if someone actually implements it in another portion of a partial class.[7]

    1.分部方法 (Partial methods) 必须定义在分部类 (partial classes) 中
    2.定义分部方法 需要用 partial 做修饰符
    3.分部方法不一定总是有执行内容的,也就是说定义的方法 可以一句操作语句都没有
    4.分部方法返回值必须是void
    5.分部方法可以是静态 (static) 方法
    6.分部方法可以包含参数,参数可以包含以下修饰词:this,ref,params
    7.分部方法必须是私有 (private) 方法
    例子:

    partial class C
    {
        static partial void M(int i); // defining declaration
    }
    partial class C
    {
        static partial void M(int i)
        {
            dosomething();
        }
    }

    很多人对c#的概念和特性还不是很了解,这里做简单说明,欢迎补充!

  • 相关阅读:
    二叉查找中使用位运算符
    Python2021专业版激活码
    南邮计算机方向
    7.字符串、异常处理、文件和流(C++学习笔记)
    6.多态与抽象(C++学习笔记)
    5.对象类与继承(C++学习笔记)
    4.数组与指针(C++学习笔记)
    3.C++函数(C++学习笔记)
    2.C++控制语句(C++学习笔记)
    1.基本知识(C++学习笔记)
  • 原文地址:https://www.cnblogs.com/softwarelanguagebs/p/2120718.html
Copyright © 2011-2022 走看看