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);
    }
  • 相关阅读:
    这段时间的总结以及未来一个月的计划
    通过配置文件构建XML
    利用汇编实现表驱动
    Intel汇编语言程序设计课后习题,6.5.5
    盲目地相信网上评价未必是好事
    ObjectiveC基础语法复习笔记
    IOS6.0 学习第1篇,基础的IOs框架
    IOS6.0 学习第2篇,弹出AlertView
    Android Fragment的使用(1)
    ObjecteiveC 属性修饰符
  • 原文地址:https://www.cnblogs.com/shapaozi/p/7875096.html
Copyright © 2011-2022 走看看