c# - 我怎么知道使用了默认值?

标签 c# .net

考虑这样的方法:

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/

相关文章:

c# - 比较 .NET 中的字符串

C# 枚举查询 linq 和通用类型?

c# - AutoPostback 没有正确设置焦点

c# - Azure 应用服务容器上的 ASP.net core docker https

c# - .net Core 中的自定义属性设置

.net - WPF/Silverlight 世界之外的 INotifyPropertyChanged 用法

c# - .NET 4.0 中的 Assembly.LoadFrom() 权限

c# - 如何绘制选定的文本

c# - 通过队列消息进行负载均衡时如何处理自动生成的 ID?

c# - 如何访问 "Documents and Settings"文件夹?