如何识别方法是否访问默认值
本文关键字:方法 是否 访问 默认值 识别 何识别 | 更新日期: 2023-09-27 18:31:21
我有一个名为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");
因为在这种情况下,该方法实际上 访问传递的值,但我的条件会说它正在访问 默认值
+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);
}
正如Sinatr在评论中提到的,重载该方法可能是最有效的方法。然后,这两个重载都可以将控制汇集到单个内部方法中,指示是否使用了默认值:
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
}
}