【问题标题】:How to identify whether the method accessing the default value or not如何判断方法是否访问默认值
【发布时间】:2016-04-27 16:57:06
【问题描述】:

我有一个名为myStaticMethod 的静态方法。其定义如下:

 public static void myStaticMethod(string strInputVal="Default")
        {       
            if ("Is accessing Default Value") // how can i define this condition
            {
                //Do something
            }
            else
            {
                //Do some other task
            }
        }

现在我可以通过以下不同方式调用该方法:

 myStaticMethod(); // will access default value
 myStaticMethod("Some Value");// will use the passed value
 myStaticMethod("Default"); // Here passing value and default value are same

我的问题是如何识别该方法是访问默认值还是通过方法调用传递的值。

如果我将条件定义为;

 if (strInputVal == "Default")
    {
       // do operation here
    }

这对于所有函数调用都意味着完整 myStaticMethod("Default"); 因为在这种情况下,方法实际上 访问传递的值,但我的条件会说它正在访问 默认值

【问题讨论】:

  • 没有办法区分myStaticMethod()myStaticMethod("Default"),你必须使用方法重载(创建2个方法:无参数和一个有参数),不要在这种情况下使用带默认值的参数。
  • @Sinatr 把它写下来作为答案,它几乎是正确的。
  • @Sinatr 我已经根据您的评论写了一个答案,希望您不介意;如果你这样做,我会删除它。
  • @AdrianWragg,你是非常友善的声誉忍者;)。我不介意,否则你会看到我的答案。

标签: c# function parameters default-value


【解决方案1】:

+1 @Sinatr 我只会添加说明。:

public static void myStaticMethod(string strInputVal)
{
    // Do what same part
}

// When you call this method it is 
public static void myStaticMethod()
{
    string strInputVal = "Default";   
    //Do something for default value
    System.Console.WriteLine("I am indetified as called with default value");
    myStaticMethod(strInputVal);
}

【讨论】:

    【解决方案2】:

    正如 Sinatr 在 cmets 中提到的,重载方法可能是最有效的方法。然后,两个重载都可以将控制集中到一个内部方法中,指示是否使用默认值:

    public static void myStaticMethod()
    {
        myInternalStaticMethod ("Default", true);
    }
    
    public static void myStaticMethod(string inputValue)
    {
        myInternalStaticMethod (inputValue, false);
    }
    
    private static void myInternalStaticMethod(string inputValue, bool isDefault)
    {
        if (isDefault) {
                //Do something
        } else {
                //Do some other task
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2012-01-05
      • 2012-01-29
      • 2013-01-17
      • 2011-01-14
      • 2011-03-04
      • 1970-01-01
      • 2018-09-15
      • 2012-12-31
      相关资源
      最近更新 更多