我怎么知道使用默认值?

时间:2015-08-24 05:14:46

标签: 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()不同。

6 个答案:

答案 0 :(得分:67)

没有,也不应该有任何理由这样做。默认值就是这样做 - 当没有指定时提供默认值。

如果你需要根据传递的内容执行不同的功能,我建议重载方法。例如:

void addCost(int x, int y,String itemName){
double cost = x*y + originalCost
Item item = SoldItem.findByItemName(itemName)
item.price += cost
}

或者,如果存在共享逻辑,则可以使用其他参数:

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()

答案 1 :(得分:10)

您的答案可能类似于以下代码。

public void CommonOperations(/*Some parameteres as needed.*/)
{
    // Shared operations between two methods.
}
public void WorkAt()
{
    string location = "home";
    CommonOperations(/*Some parameteres as needed.*/);
    //do something
}

public void WorkAt(string location)
{
    CommonOperations(/*Some parameteres as needed.*/);
    //do the other thing
}

我希望它会有所帮助。

答案 2 :(得分:7)

使用sentinel值而不是默认值

public void WorkAt(location="default_sentinel_value") {
    if (location == "default_sentinel_value") {
        location = "home";
        ...
    }
    else
    {
        ...
    }
}

答案 3 :(得分:2)

作为程序员,默认值是已知值,因此您可以像以下任何方法一样进行编码:

方法1:

public void WorkAt(string location = @"home")
{
    if (location == @"home")
    {
        // Do something
    }
    else
    {
        // Do another thing
    }
}

方法2:使用功能超载

//function(A) with default value
public static void samplemethod()
    {
       string defaultValue="home";
       //Do something
    }

//function (B) without default value
public static void samplemethod(string x)
    {
         //Do something
    }

然后samplemethod("someValue");将致电function(B)samplemethod();会致电function(A)

答案 4 :(得分:2)

如果使用OO,则可以创建一些GetSet属性。

private string pvt_default;
private string pvt_location;
public string location
{
    get
    {
        return this.pvt_location;
    }
    set
    {
        if (pvt_default == location)
        {
            // do somthing
        }
        this.pvt_location = location;
    }
}

答案 5 :(得分:2)

将默认值更改为null并将其更改为@“home”

相关问题