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

這可以用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM