• C# 3.0新加特性


    类型推断

    申明变量的时候,可以不用直指定类型:

    var i = 5;
    var s = "Hello";
    //两种写法是一样的
    int i = 5;
    string s = "Hello";

    类型推断也支持数组:

    var b = new[] { 1, 1.5, 2, 2.5 };            // double[]
    var c = new[] { "hello", null, "world” };      // string[]

    扩展方法

    扩展方法必须被定义在静态类中,并且必须是非泛型、非嵌套的静态类。例如:

    public static class JeffClass
    {
        public static int StrToInt32(this string s)
        {
            return Int32.Parse(s);
        }
    
        public static T[] SomeMethd<T>(this T[] source, int pram1, int pram2)
        {
            /**/
        }
    }

    上面一个是给string类型的对象添加了一个方法,另一个是给所有类型的数组添加了一个方法,方法有两个整型参数。

    扩展方法只在当前的命名空间类有效,如果所在命名空间被其它命名空间import引用了,那么在其它命名空间中也有效。扩展方法的优先级低于其它的常规方法,也就是说如果扩展方法与其它的方法相同,那么扩展方法不会被调用。

    Lamda表达式

    可以看成是对匿名方法的一个语法上的简化,但是λ表达式同时可以装换为表达式树类型。

    对象和集合的初始化

    var contacts = new List<Contact> {
       new Contact {
          Name = "Chris",
          PhoneNumbers = { "123455", "6688" }
       },
       new Contact {
          Name = "Jeffrey",
          PhoneNumbers = { "112233" }
       }
    };

    匿名类型

    var p1 = new { Name = "Lawnmower", Price = 495.00 };
    var p2 = new { Name = "Shovel", Price = 26.95 };
    p1 = p2;

    自动属性

    会自动生成一个后台的私有变量

    public Class Point
    {
       public int X { get; set; }
       public int Y { get; set; }
    }

    查询表达式

    这个其实就是扩展方法的运用,编译器提供了相关的语法便利,下面两端代码是等价的:

    from g in
       from c in customers
       group c by c.Country
    select new { Country = g.Key, CustCount = g.Count() }
    
    customers.
    GroupBy(c => c.Country).
    Select(g => new { Country = g.Key, CustCount = g.Count() })

    表达式树

    Func<int,int> f = x => x + 1;
    Expression<Func<int,int>> e = x => x + 1; 
  • 相关阅读:
    split 使用
    python中接受上一条命令执行的结果----subprocess.check_output()
    k8s开启cadvisor http 服务
    Spring Cloud之配置中心搭建
    如何高效地学习开源项目
    Spring Boot之默认连接池配置策略
    Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: ..... this is incompatible with sql_mode=only_full_group_by
    com.netflix.zuul.exception.ZuulException: Forwarding error
    设置环境变量相关命令
    java.lang.NoClassDefFoundError: org/springframework/web/context/WebApplicationContext
  • 原文地址:https://www.cnblogs.com/kylin2016/p/5817045.html
Copyright © 2020-2023  润新知