zoukankan      html  css  js  c++  java
  • Default

    从 C# 7.1 开始,当编译器可以推断表达式的类型时,文本 default 可用于默认值表达式。 文本 default 生成与等效项 default(T)(其中,T 是推断的类型)相同的值。 这可减少多次声明类型的冗余,从而使代码更加简洁。 文本 default 可用于以下任一位置:

    • 变量初始值设定项
    • 变量赋值
    • 声明可选参数的默认值
    • 为方法调用参数提供值
    • 返回语句(或 expression bodied 成员中的表达式)

    以下示例展示了文本 default 在默认值表达式中的多种用法:

    public class Point
    {
        public double X { get; }
        public double Y { get; }
    
        public Point(double x, double y)
        {
            X = x;
            Y = y;
        }
    }
    
    public class LabeledPoint
    {
        public double X { get; private set; }
        public double Y { get; private set; }
        public string Label { get; set; }
    
        // Providing the value for a default argument:
        public LabeledPoint(double x, double y, string label = default)
        {
            X = x;
            Y = y;
            this.Label = label;
        }
    
        public static LabeledPoint MovePoint(LabeledPoint source, 
            double xDistance, double yDistance)
        {
            // return a default value:
            if (source == null)
                return default;
    
            return new LabeledPoint(source.X + xDistance, source.Y + yDistance, 
            source.Label);
        }
    
        public static LabeledPoint FindClosestLocation(IEnumerable<LabeledPoint> sequence, 
            Point location)
        {
            // initialize variable:
            LabeledPoint rVal = default;
            double distance = double.MaxValue;
    
            foreach (var pt in sequence)
            {
                var thisDistance = Math.Sqrt((pt.X - location.X) * (pt.X - location.X) +
                    (pt.Y - location.Y) * (pt.Y - location.Y));
                if (thisDistance < distance)
                {
                    distance = thisDistance;
                    rVal = pt;
                }
            }
    
            return rVal;
        }
    
        public static LabeledPoint ClosestToOrigin(IEnumerable<LabeledPoint> sequence)
            // Pass default value of an argument.
            => FindClosestLocation(sequence, default);
    }
  • 相关阅读:
    创建对象的模式
    linux下安装node v12.16.3
    es6知识点总结
    在阿里云上部署的node服务器不能通过公网IP访问
    angular 1 input中选中状态绑定
    让一个元素水平垂直居中
    语录收集
    跨域
    事件循环
    git的常用命令
  • 原文地址:https://www.cnblogs.com/shapaozi/p/7875096.html
Copyright © 2011-2022 走看看