考虑这样的方法:
public void WorkAt(string location = @"home")
{
//...
}
它可以通过显式传递一个值来调用,例如:
WorkAt(@"company");
WorkAt(@"home");
或者只使用默认值,例如:
WorkAt();
有没有办法知道是否使用默认值?
例如,我想这样编码:
public void WorkAt(string location = @"home")
{
if ( /* the default value is used unexplicitly */)
{
// Do something
}
else
{
// Do another thing
}
}
请注意 WorkAt("home")
在此上下文中不同于 WorkAt()
。
最佳答案
没有也不应该有任何理由这样做。默认值就是这样做的 - 在未指定时提供默认值。
如果您需要根据传递的内容执行不同的功能,我建议重载该方法。例如:
public void WorkAt()
{
//do something
}
public void WorkAt(string location)
{
//do other thing
}
或者,如果存在共享逻辑,您可以使用附加参数:
public void WorkAt(string location = "home", bool doOtherThingInstead = false)
{
if (!doOtherThingInstead)
{
//do something
}
else
{
//do other thing
}
//do some shared logic for location, regardless of doOtherThingInstead
}
作为旁注,也许问题中的示例是人为设计的,但是 WorkAt()
没有指定参数没有词法意义。人们会期望在单词 at 之后有一个值。也许您可能想重命名第二个方法 WorkAtDefaultLocation()
。
关于c# - 我怎么知道使用了默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32174851/