C# 如何使参数发挥作用。
当你有这样的代码时
static string Concat(int arg)
{
return arg.ToString();
}
static string Concat(int arg, params string[] p)
{
string result = string.Empty;
result = result + arg.ToString();
foreach (var s in p)
{
result = result + s;
}
return result;
}
Resharper 表示带有参数的方法隐藏了另一个方法。这是否意味着在幕后正在定义另一种方法并调用参数传递空数组的方法?或者完全是别的什么?
(请不要陷入蹩脚的代码 - 这只是一个例子)
编辑解释:
如果我没有定义静态字符串 Concat(int arg) 方法,我仍然可以将第二个方法调用为
var s = Concat(123);
尽管该方法没有被定义......所以问题是:第一个方法是否在幕后隐式定义并使用空数组调用第二个方法。请注意,我将 arg 类型从 string 更改为 int。
解释一下我所看到的奇怪之处。当您按上面的方式调用时...它会使用空数组命中 params 对象,该 param 不为空 - 这是我所期望的。当我第一次编写 foreach 循环时,我对参数进行了空检查,然后发现我不需要它。
所以...您认为它必须在数组中的第一个参数之后包装任何参数,对吗?一点内联代码? ...所以如果您传入“dave”,您将得到 freddave 作为输出....
但是将 null 传递给它......
static void Main(string[] args)
{
Console.WriteLine(Concat("fred",null));
}
//static string Concat(string arg)
//{
// return arg;
//}
static string Concat(string arg, params int[] p)
{
string result = string.Empty;
result = result + arg;
if (p != null)
{
foreach (var s in p)
{
result = result + s.ToString();
}
}
return result;
}
你发现在这种情况下p实际上是空的...... 如果您使用字符串 example ... id of Expected an array with 1 element of null ... 而整个 params 对象为 null。
最佳答案
说实话,我认为称之为“隐藏”是有误导性的。
这两个方法肯定都会创建,但是如果你调用:
Concat(5);
那么对于该调用,两种方法都适用(按照 C# 规范第 7.5.3.1 节的术语),但第一个方法更好(第 7.5.3.2 节)因为这个:
- Otherwise, if MP is applicable in its normal form and MQ has a
params
array and is applicable only in its expanded form, then MP is better than MQ.
因此在这种情况下,将调用第一个方法。
如果不指定至少一个字符串,则无法使用 params
扩展调用第二个方法。当然,它仍然可以用空数组调用:
Concat(5, new string[0]);
关于c# - params 在 C# 中如何工作(据称一种方法隐藏了另一种方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19177159/