为什么 null 类型的值不能用作 double 类型的默认参数?

Why a value of type null cannot be used as a default parameter with type double?

快速提问:

MSDN - Named and Optional Arguments (C# Programming Guide) 明确表示

"Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates."

所以不是这个:

class MyClass
{

//..

public MyClass() { // Empty Constructor's Task }
public MyClass(SomeType Param1) { // 2nd Constructor's Task }
public MyClass(SomeType Param1, SomeType Param2) { // 3rd Constructor's Task }
}

我应该可以做到:

class MyClass
    {
        //..

        public MyClass(SomeType Param1 = null, SomeType Param2 = null)
        {
            if (Param1)
            {
                if (Param2)
                {
                    // 3rd constructor's Task
                }
                else
                {
                    // 2nd constructor's Task
                }
            }
            else
            {
                if (!Param2)
                {
                    // Empty constructor's Task
                }
            }

        }
    }

那为什么这不起作用:

public MyClass(double _x = null, double _y = null, double _z = null, Color _color = null)
{
   // ..
}

告诉我:

A value of type "null" cannot be used as a default parameter because there are no standard conversions to type 'double'

double 是 shorthand 的 value type. You'd need to wrap it in Nullable<T>?,表示它可以为 null。

public MyClass(double? _x = null, double? _y = null, double? _z = null, Color _color = null)
{
   // ..
}

正如 David 在他的回答中所解释的那样,Double 不是可空类型。为了给它分配一个空值,你必须将 Double 转换为 System.Nullable<double>double?

完整答案类似于:

public void MyMethod(double? param = null) { }

这里明显的问题是,您必须向它传递一个 double? 值,而不是只传递一个 double 值。

我不确定此功能的确切范围,但您始终可以参考默认值。例如:

public void MyMethod(double param = double.MinValue) 
{ 
    if (param == double.MinValue) 
        return; 
}

或类似的东西。