[英]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.