简体   繁体   English

传递默认参数值(不管它是什么)

[英]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);

Can this be done in C#? 这可以用C#完成吗?

You might say, "if you don't want to set the parameter, just call the method without it". 您可能会说,“如果您不想设置参数,只需在没有它的情况下调用方法”。 But then I get ugly IFs like this in my code: 但后来我在我的代码中得到了这样丑陋的IF:

//kinda ugly :(
if(parameterIsSet)
    DoSomething(a, myValue);
else
    DoSomething(a);

When I could do this instead: 当我能做到这一点时:

DoSomething(a, b: parameterIsSet ? myValue : default);

I can of course do this: 我当然可以这样做:

DoSomething(a, b: parameterIsSet ? myValue : 42);

But I don't want to hardcode "42" in two places 但我不想在两个地方硬编码“42”

In a case like this, I would usually use null as mentionned in a comment. 在这种情况下,我通常会在评论中提到使用null Thus the code would look like this: 因此代码看起来像这样:

public void DoSomething(int a, int? bOverwrite = null)
{
    int b = bOverwrite ?? 42;
    // remaining code as before...
}

In such case, you would generally remove parameterIsSet variable and initialize a variable with null and set a value if necessary: 在这种情况下,您通常会删除parameterIsSet变量并使用null初始化变量并在必要时设置值:

int? myB = null;
if (/* some condition */)
{
    myB = 29;
}

DoSomething(a, myB);

If you still have parameterIsSet , you could call the function like this: 如果你还有parameterIsSet ,你可以调用这样的函数:

DoSomething(a, parameterIsSet ? b : default(int?));

Other alternatives: 其他替代品:

If you have many such parameters, it might be simpler to create a class for parameters and set its default in constructor: 如果你有很多这样的参数,为参数创建一个类并在构造函数中设置它的默认值可能更简单:

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);

And if some cases, the ugly IFs might be the best solution as many times, you might use the same condition to initialize b anyway or you need more variables to keep track of everything and the final code might be even uglier than the ugly code. 如果有些情况下,丑陋的IF可能是最好的解决方案,你可能会使用相同的条件来初始化b ,或者你需要更多的变量来跟踪所有内容,最终的代码甚至可能比丑陋的代码更丑。

if (/* some condition */)
{
    int b = some_complet_expression;
    DoSomething(a, b);

    // Some other stuff here....
}
else
{
    DoSomething(a);

    // Different stuff here...
}

In particular, if you would have other code that depend on the condition after the call, it might be the base solution. 特别是,如果您在调用后有其他依赖于条件的代码,那么它可能是基本解决方案。 Each case is specific. 每个案例都是具体的。 With experience, you learn how to write best code for the situation. 凭借经验,您将学习如何为这种情况编写最佳代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM