为什么空传递到PARAMS方法,结果在一个空参数数组?数组、参数、结果、方法

2023-09-03 11:52:22 作者:呐谁、咱娶你

我有一个使用 PARAMS 关键字,像这样的方法:

I have a method that uses the params keyword, like so:

private void ParamsMethod(params string[] args)
{
    // Etc...
}

然后,我使用的参数不同组合调用方法:

Then, I call the method using various combinations of arguments:

                            // Within the method, args is...
ParamsMethod();             // - a string array with no elements
ParamsMethod(null);         // - null (Why is this?)
ParamsMethod((string)null); // - a string array with one element: null
ParamsMethod(null, null);   // - a string array with two elements: null and null
ParamsMethod("s1");         // - a string array with one element: "s1"
ParamsMethod("s1", "s2");   // - a string array with two elements: "s1" and "s2"

我了解所有的情况下,除了第二个。有人可以解释为什么 ParamsMethod(空)引起的args ,而不是一个一个空元素的数组?

I understand all of the cases, except for the second one. Can someone explain why ParamsMethod(null) causes args to be null, instead of an array with one null element?

推荐答案

A PARAMS 参数只是为了提供指定值的一种便捷方式 - 你仍然可以传递一个直接数组引用。

A params parameter is only meant to provide a convenient way of specifying values - you can still pass an array reference directly.

现在,可转换为的String [] 字符串,所以两者间pretations是有效的 - 它是由这是preferred规范。在第10.6.1.4该规范规定:

Now, null is convertible to either string[] or string, so both interpretations are valid - it's up to the spec which is preferred. The spec states in section 10.6.1.4 that:

  

给出一个参数数组的参数可以是一个单一的前pression是隐式转换为参数数组类型。在这种情况下,参数数组的作用precisely像值参数。

The argument given for a parameter array can be a single expression that is implicitly convertible to the parameter array type. In this case, the parameter array acts precisely like a value parameter.

另外,[...]

在换言之,编译器检查以查看参数是否是有效的,正常的参数型的第一,只建立一个数组,如果它绝对有

In other words, the compiler checks to see whether the argument is valid as the "normal" parameter type first, and only builds an array if it absolutely has to.