zoukankan      html  css  js  c++  java
  • C# 6.0 (C# vNext) 的新功能:Expression Bodied Functions and Properties

    Expression Bodied Function 它可以用在:
    • methods
    • user-defined operators
    • type conversions
    • read-only properties 
    • indexers
    看下面的样例:
    public class RgbColor(int r, int g, int b)
    {
      public int Red { get; } = r;
      public int Green { get; } = g;
      public int Blue { get; } = b;
     
      public string ToHex() =>
        string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue);
     
      public static RgbColor operator - (RgbColor color) =>
        new RgbColor(
          color.Red ^ 0xFF,
          color.Green ^ 0xFF,
          color.Blue ^ 0xFF
        );
    }

    用於「方法」的样例:
    public string ToHex() => string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue);
    public override string ToString() => this.Name;

    用於「user-defined operators」的样例:
      public static RgbColor operator - (RgbColor color) =>
        new RgbColor(
          color.Red ^ 0xFF,
          color.Green ^ 0xFF,
          color.Blue ^ 0xFF
        );

    public static Complex operator +(Complex a, Complex b) => a.Add(b);

    用於「read-only property」的样例:
    特别注意,这是 Read Only Property 而不是 Field 
    public string ID => Guid.NewGuid().ToString();
    又一个样例:
    public class Point(int x, int y) {
        public int X => x;
        public int Y => y;
        public double Dist => Math.Sqrt(x * x + y * y);
        public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
    }

    用於「type conversions」的样例:实现 string 和 Name 之间的隐性转换
    public static implicit operator string(Name n) => n.First + " " + n.Last;


    用於「indexers」的样例:

    public Customer this[Id id] => store.LookupCustomer(id);







    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    (转)干货|一次完整的性能测试,测试人员需要做什么?
    (转)JMeter性能测试-服务器资源监控插件详解
    【Android Apk重新签名报错re-sign.jar之解决方法】
    CrackMe_001
    判断二叉树是否是镜像对称
    顺时针打印矩阵
    利用前序遍历和中序遍历构造二叉树
    二叉树的四种遍历方式
    最长回文子串
    同步/异步/阻塞/非阻塞
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4915100.html
Copyright © 2011-2022 走看看