.NET 4的String []参数的默认值设置 [英] .net 4 string[] parameter default value setting

查看:136
本文介绍了.NET 4的String []参数的默认值设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着这样做:

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

但它告诉我,我不能这样做呢? 为什么会这样?

but it tells me that I can't do that ? why is that so ?

推荐答案

现在的问题是,默认的参数必须是常量。在这里,你是动态分配的数组。正如声明常量变量,引用类型只字符串和空值的支持。

The problem is that the default arguments must be constants. Here you are dynamically allocating an array. As with declaring const variables, for reference types only string literals and nulls are supported.

您可以通过以下方式实现这一目标。

You can achieve this by using the following pattern

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

现在,当主叫用户排除参数在调用点,编译器将传递值然后你就可以处理的需要。需要注意的是仅仅指刚要保持它的简单我已经修改了函数的参数的值,而不是通常认为好的做法,但我相信这可能是正常的在这种情况下。

Now when the caller excludes the argument at the call site, the compiler will pass the value null which you can then handle as required. Note that jsut to keep it simple I have modified the value of the argument in the function, not generally considered good practice but I believe this might be alright in this scenario.

这篇关于.NET 4的String []参数的默认值设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆