在方法调用中初始化字符串数组作为C#中的参数
如果我有这样的方法:
public void DoSomething(int Count, string[] Lines) { //Do stuff here... }
为什么我不能这样称呼它?
DoSomething(10, {"One", "Two", "Three"});
什么是正确的(但希望不是很长的路)?
你可以这样做 :
DoSomething(10, new[] {"One", "Two", "Three"});
如果所有对象都是相同类型,则不需要在数组定义中指定类型
如果DoSomething
是您可以修改的函数,则可以使用params
关键字传递多个参数而不创建数组。 它也将正确接受数组,因此不需要“解构”现有数组。
class x { public static void foo(params string[] ss) { foreach (string s in ss) { System.Console.WriteLine(s); } } public static void Main() { foo("a", "b", "c"); string[] s = new string[] { "d", "e", "f" }; foo(s); } }
输出:
$ ./d.exe 一个 b C d Ë F
试试这个:
DoSomething(10, new string[] {"One", "Two", "Three"});
您可以在传递它的同时构建它:
DoSomething(10, new string[] { "One", "Two", "Three"});