C# .net 4字符串[]参数默认值设置

C# .net 4字符串[]参数默认值设置,c#,.net,.net-4.0,C#,.net,.net 4.0,我试着这样做: public int Insert(object o, string[] ignore = new string[] {"Id"}) Insert(obj); Insert(obj, "str"); Insert(obj, "str1", "str2"); 但它告诉我我不能那样做? 为什么会这样?问题是默认参数必须是常量。这里是动态分配数组。与声明const变量一样,对于引用类型,只支持字符串文本和空值 您可以通过使用以下模式来实现这一点 public int Ins

我试着这样做:

public int Insert(object o, string[] ignore = new string[] {"Id"})
Insert(obj);

Insert(obj, "str");

Insert(obj, "str1", "str2");  
但它告诉我我不能那样做?
为什么会这样?

问题是默认参数必须是常量。这里是动态分配数组。与声明
const
变量一样,对于引用类型,只支持字符串文本和空值

您可以通过使用以下模式来实现这一点

public int Insert(object o, string[] ignore = null)
{
  if (ignore == null) ignore = new string[] { "Id" };
  ...
  return 0;
}

现在,当调用方在调用站点排除参数时,编译器将传递值
null
,然后您可以根据需要处理该值。注意,jsut为了保持简单,我修改了函数中参数的值,这通常不被认为是好的做法,但我相信在这种情况下这可能没问题。

引用类型唯一可用的默认值是null(除了也接受文本的字符串),因为它必须在编译时可用

最简单的解决方案是使用.Net 1.1方式:

public int Insert(object o)
{
    return Insert(o, new String[] { "Id" });
}


public int Insert(object o, String[] s)
{
    // do stuff
}

既然这是一个数组,为什么不使用
params

public int Insert(object o, params string[] ignore)
{
    if (ignore == null || ignore.Length == 0)
    {
        ignore = new string[] { "Id" };
    }
    ...
然后你可以这样称呼它:

public int Insert(object o, string[] ignore = new string[] {"Id"})
Insert(obj);

Insert(obj, "str");

Insert(obj, "str1", "str2");  

请发布您的编译器错误:)@Spence它只是告诉我,除了字符串之外,引用类型不允许这样做,我只是有点惊讶,因为某种原因没有实现“错误CS1736:默认参数值必须是编译时常量”。这就是答案……是的,我喜欢这个忽略=忽略??新[]{“Id”};,为什么.net开发团队不能这样做呢_O@Omu例如,因为它意味着不能将
null
用作实际值。您仍然可以使用重载执行类似的操作。实际上它是c#1到3.5的方式…:)它总是令人困惑。也许没有两个参数,但假设有5个参数是可选的,这是很多重载。。。