C# 使用参数 string[] 将 string[] 数组分配给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15757216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:51:39  来源:igfitidea点击:

Assigning string[] array into a function with params string[]

c#stringparams

提问by Yuen Li

I have a function void Test(int id, params string[] strs).

我有一个功能void Test(int id, params string[] strs)

How would I pass an array of strings as the strsargument? When I call:

我如何将字符串数组作为strs参数传递?当我打电话时:

Test(1, "a, b, c");

It takes "strs" as a single string (not an array).

它将“strs”作为单个字符串(不是数组)。

回答by jordanhill123

I tested this and it works:

我测试了这个并且它有效:

    private void CallTestMethod()
    {
        string [] strings = new string [] {"1", "2", "3"};
        Test(1, strings);

    }

    private void Test(int id, params string[] test)
    {
        //Do some action with input
    }

You can call it just like this Test(1, <Some string[]>);

你可以这样称呼它 Test(1, <Some string[]>);

Edit

编辑

From MSDN website on params:

MSDN 网站上的 params

The params keyword lets you specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

params 关键字允许您指定一个方法参数,该参数采用可变数量的参数。您可以发送以逗号分隔的参数声明中指定类型的参数列表,或指定类型的参数数组。您也可以不发送任何参数。方法声明中的 params 关键字后不允许附加参数,并且方法声明中只允许一个 params 关键字。

So you could also call the Testmethod like this Test(1);without compiler errors.

所以你也可以Test像这样调用方法 Test(1);而不会出现编译器错误。

回答by illegal-immigrant

Actually, the paramsis just a syntactic sugar handled by the C# compiler, so that

实际上,这params只是由 C# 编译器处理的语法糖,因此

this:

这个:

void Method(params string[] args) { /**/ }
Method("one", "two", "three");

becomes this:

变成这样:

void Method(params string[] args) { /**/ }
Method(new string[] { "one", "two", "three" })

回答by fhnaseer

Try out this.

试试这个。

var myStringArray = new string[] {"a", "b", "c"};
Test(myStringArray)