我想知道参数 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/