如何将null的equivalant指定为结构类型的默认参数

本文关键字:结构 类型 参数 默认 null equivalant | 更新日期: 2023-09-27 18:26:58

如何定义一个函数,以便可以选择性地传递结构参数,同时能够在函数内部知道它是否被传递?我试图实现的目标类似于:

function SomeFunction(string str = null)
{
    if (str == null) { ... }
}

在没有参数的情况下调用上述函数将触发if (str == null)...条件:

SomeFunction();

上面的方法不适用于struct类型的参数。给定以下结构:

public struct MyStruct
{
    public int SomeInt;
    public double SomeDouble;
}

这会产生一个没有标准转换的错误:

public function SomeFunction(MyStruct mystruct = null) { }

但当我将函数定义为:

public function SomeFunction(MyStruct mystruct = default(MyStruct)) { }

并用调用函数

SomeFunction();

在进入函数mystruct时,SomeInt包含0,SomeDouble包含0.00。这些可能是合法的值,这让我无法知道参数是否真的传递给了函数或为空。

我如何定义这个参数,以便如果调用中没有指定它,我可以在函数中检测到它?

如何将null的equivalant指定为结构类型的默认参数

使用可为null的类型(可选地使用重载方法,如下面DoSomething所示)来检查是否传递了值。

public function SomeFunction(MyStruct? mystruct)
{
   if(mystruct.HasValue)
       DoSomething(mystruct.Value);
   else
       DoSomething();
}
public function SomeFunction(MyStruct? mystruct) { }

您可以使用可为null的类型