c# - 在c#中使用[可选]参数后如何知道它是否由调用方法给出?

标签 c# optional-parameters

我想知道参数 b 是否由调用方法提供,以便我可以根据它在方法定义中对其进行条件处理。 因为这里总是有一个“b”的默认值 0 但我想区分用户调用 cc(5,0) 和 cc(5)。

有什么办法知道吗?

     class Program
        {
            static void Main(string[] args)
            {
               var c= cc(5);
            }
            public static int cc(int a, [Optional] int b)
            {
              int c=0;
            //if(b is provided)
              c = a * b;
            //else()
              c =a*a;    
              return c;
            }
        }

最佳答案

你不能,通过那个机制。即使你使用了 int? b = null,调用者可以明确指定 null。要知道,您必须使用重载而不是可选参数,例如:

public static int cc(int a) => cc(a, 0, false);
public static int cc(int a, int b) => cc(a, b, true);
private static int cc(int a, int b, bool bSpecified) // could also use int? here
{...}

关于c# - 在c#中使用[可选]参数后如何知道它是否由调用方法给出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69218407/

相关文章:

c# - 仅当使用 Process.Start() 在 C# 中作为外部程序运行时,C 控制台程序才会在退出时崩溃(访问冲突)

c# - 如何使正则表达式仅与 = 之前只有一个字母的模式匹配

php - 调用函数时如何省略中间参数的默认值?

java - 可选的 <String> 映射函数返回 null

python - 可选参数如何变成必需参数?

go - 在 gomail v2 中发送带有可选附件的电子邮件

c# - 无法将数据绑定(bind)到中继器内的标签

c# - 删除行,重新播种非 PK 索引列? C#

c# - FluentValidation - 内部集合未验证

caching - CachePut 跳过必填字段