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);
}
原文地址:https://www.cnblogs.com/shapaozi/p/7875096.html