[英]C# not passing parameters if those parameters are optional
我希望這是一個簡單的問題,只是我的大腦缺少最后一個環節。 如果其他地方還有其他問答,請指向我並關閉此...但我在任何地方都找不到。
這是要點:
我有一個帶有可選參數的方法的類,類似於
public class Test
{
public void Method(string required, string someoptionalparameter="sometext", string anotheroptionalparameter="someothertext")
{
// do something here with the parameters
}
}
到目前為止,很好。
現在,我將實例化該類並在我的代碼中調用該方法:
...
Test.Method("RequiredString");
這將起作用。 如果我提供可選參數,它仍然可以工作。
但是我如何處理一個場景,我不知道是否實際提供了可選值。 所以例如:
...
Test.Method(requiredString,optionalString1,optionalString2);
...
如果我不知道 optionalString1 和 optionalString2 是否有值怎么辦? 那么我是否需要為每個場景編寫一個覆蓋,沿着......
if (optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString);
}
else if ((!optionalString1.isEmpty() && optionalString2.isEmpty())
{
Test.Method(requiredString, optionalString1);
}
else if...
必須有另一種方式,我敢打賭這很簡單,我只是有一個星期五......有沒有像......
Test.Method(requiredStrinig, if(!optionalString1.isEmpty())...
您應該反轉邏輯 - 讓那些可選參數為空,然后在方法中進行檢查。 所以在你的情況下,方法應該是這樣的:
public void Method(string required, string opt1 = null, string opt2 = null)
{
opt1 = opt1 ?? "some default non-null value if you need it";
opt2 = opt2 ?? "another default value, this one for opt2";
// for those not knowing what it does ?? is basically
// if (opt1 == null) { opt1 = "value"; }
//... rest of method
}
然后在外部代碼中調用該方法會更容易,並且方法內的邏輯將能夠處理空情況。 在方法之外,您無需擔心那些額外的參數,即您可以以任何方式調用該方法,例如:
Test.Method(requiredString);
Test.Method(requiredString, "something");
Test.Method(requiredString, null, "something else");
同樣正如@Setsu 在評論中所說,您可以這樣做以避免將 null 作為第二個參數傳遞:
Test.Method("required", opt2: "thanks @Setsu");
改用重載,它會為您提供更好的語義,如果您從客戶端代碼中猜測參數,您就可以確定要使用什么重載,此外,您將在一個地方擁有所有機器,查看此技術,希望這會有所幫助,問候。
課程計划{
static void Main(string[] args) {
Work("Hi!");
}
private static void Work(String p1) {
Work(p1, null, null);
}
private static void Work(String p1, String p2) {
Work(p1, p2, null);
}
private static void Work(String p1, String p2, String p3) {
if ( String.IsNullOrWhiteSpace(p2) ) p2 = String.Empty;
if ( String.IsNullOrWhiteSpace(p3) ) p3 = String.Empty;
Console.WriteLine(String.Concat(p1, p2, p3));
}
}
可選參數,好吧,是可選的。 它們似乎是一種減少方法重載次數的方法。 如果您收到所有三個參數,則必須決定第二個或第三個參數是否為空並需要設置為它們的“默認”值。
我的建議是你用三個字符串調用你的方法,並在方法中決定是否必須更改字符串二和三的值。 我可能會使用 const 或 readonly 而不是默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.