【发布时间】:2013-10-07 07:09:44
【问题描述】:
当参数是字典类型时,如何为操作设置默认参数值?
例如:
public void Test(Dictionary<int, bool> dic) {
...
}
【问题讨论】:
-
该方法签名无效。你想达到什么目的?
标签: c# methods parameters default-value
当参数是字典类型时,如何为操作设置默认参数值?
例如:
public void Test(Dictionary<int, bool> dic) {
...
}
【问题讨论】:
标签: c# methods parameters default-value
你不能给它一个你想要的默认值,因为它必须是一个编译时间常数值,但你可以这样做:
private static bool Test(Dictionary<string, string> par = null)
{
if(par == null) par = GetMyDefaultValue();
// Custom logic here
return false;
}
【讨论】:
您可以使用null 作为特殊情况,就像在其他答案中一样,但是如果您仍然希望能够调用Test(null) 并且具有与调用Test() 不同的行为,那么您必须链接重载:
public void Test(Dictionary<int, bool> dic) {
//optional, stops people calling Test(null) where you want them to call Test():
if(dic == null) throw new ArgumentNullException("dic");
...
}
public void Test() {
var defaultDic = new Dictionary<int, bool>();
Test(defaultDic);
}
【讨论】:
Test() 应该是 sealed。
Test(null) 并且与拨打Test() 有不同的结果,这是必须的
您只能使用null 作为引用类型的默认参数值。
默认值必须是以下表达式类型之一:
一个常量表达式;
new ValType()形式的表达式,其中ValType是值类型,例如enum或struct;
default(ValType)形式的表达式,其中ValType是值类型。
【讨论】:
null,可以提供默认的null 和一些合理的默认值。
null 是一个有效的参数值。
null 实际上对参考参数有效。
a constant expression; 和 null 是一个常量表达式;所以我明确地这么说。
null 是一个常量表达式并且对Dictionary<int, bool> 有效,那么这一切都紧跟在“你不能”之前,所以我仍然觉得它是不清楚。
您不能将字典设置为 NULL 以外的任何值。如果您确实尝试,例如:
public void Test(Dictionary<int, bool> dic = new Dictionary<string, string> { { "1", "true" }}) 或者其他什么,那么你会看到这个错误:
“dic”的默认参数值必须是编译时常量。
所以在这种情况下,NULL 是您唯一的选择。但是,这样做是没有意义的
public void Test(Dictionary<int, bool> dic = null)
如果调用者没有实例化新实例,最坏的情况是传入的dic 无论如何都会是NULL,因此无论如何添加NULL 默认值没有任何好处。
【讨论】:
假设您想在方法签名中提供非null 默认值,您无法使用此类型执行此操作。但是,您有两种替代解决方案
立即浮现在脑海中。
1,使用带有默认值的可选参数,对于Dictionary,这必须是null(我相信除了string之外的所有其他引用类型),您需要方法内部的逻辑来处理它:
public void Test(Dictionary<int, bool> dictionary = null)
{
// Provide a default if null.
if (dictionary == null)
dictionary = new Dictionary<int, bool>();
}
或者,我会这样做,只是使用“老式”方法重载。这使您可以区分不提供参数的人和提供null 参数的人:
public void Test()
{
// Provide your default value here.
Test(new Dictionary<int, bool>();
}
public void Test(Dictionary<int, bool> dictionary)
{
}
可选参数无论如何都会编译成重载的方法,所以它们几乎 语义相同,只是您希望在哪里表达默认值的偏好。
【讨论】: