[英]Passing default parameter value (whatever it is)
//method with an optional parameter
public void DoSomething(int a, int b = 42);
//caller
DoSomething(a, b: default);
这可以用C#完成吗?
您可能会说,“如果您不想设置参数,只需在没有它的情况下调用方法”。 但后来我在我的代码中得到了这样丑陋的IF:
//kinda ugly :(
if(parameterIsSet)
DoSomething(a, myValue);
else
DoSomething(a);
当我能做到这一点时:
DoSomething(a, b: parameterIsSet ? myValue : default);
我当然可以这样做:
DoSomething(a, b: parameterIsSet ? myValue : 42);
但我不想在两个地方硬编码“42”
在这种情况下,我通常会在评论中提到使用null
。 因此代码看起来像这样:
public void DoSomething(int a, int? bOverwrite = null)
{
int b = bOverwrite ?? 42;
// remaining code as before...
}
在这种情况下,您通常会删除parameterIsSet
变量并使用null初始化变量并在必要时设置值:
int? myB = null;
if (/* some condition */)
{
myB = 29;
}
DoSomething(a, myB);
如果你还有parameterIsSet
,你可以调用这样的函数:
DoSomething(a, parameterIsSet ? b : default(int?));
其他替代品:
如果你有很多这样的参数,为参数创建一个类并在构造函数中设置它的默认值可能更简单:
class DoSomethingParameters
{
public DoSomethingParameters() { A = 12; B = 42; }
public int A { get; set; }
public int B { get; set; }
}
var parameters = new DoSomethingParameters();
parameters.A = /* something */;
if (/* some condition */ {
parameters.B = 29;
}
DoSomething(parameters);
如果有些情况下,丑陋的IF可能是最好的解决方案,你可能会使用相同的条件来初始化b
,或者你需要更多的变量来跟踪所有内容,最终的代码甚至可能比丑陋的代码更丑。
if (/* some condition */)
{
int b = some_complet_expression;
DoSomething(a, b);
// Some other stuff here....
}
else
{
DoSomething(a);
// Different stuff here...
}
特别是,如果您在调用后有其他依赖于条件的代码,那么它可能是基本解决方案。 每个案例都是具体的。 凭借经验,您将学习如何为这种情况编写最佳代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.