메서드 호출에서 문자열 배열 초기화 C#의 매개 변수로 매개 변수
-
06-07-2019 - |
문제
다음과 같은 메소드가있는 경우 :
public void DoSomething(int Count, string[] Lines)
{
//Do stuff here...
}
왜 이렇게 부를 수 없습니까?
DoSomething(10, {"One", "Two", "Three"});
옳은 것은 무엇입니까 (그러나 희망적으로 먼 길은 아님)?
해결책
you can do this :
DoSomething(10, new[] {"One", "Two", "Three"});
provided all the objects are of the same type you don't need to specify the type in the array definition
다른 팁
If DoSomething
is a function that you can modify, you can use the params
keyword to pass in multiple arguments without creating an array. It will also accept arrays correctly, so there's no need to "deconstruct" an existing array.
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);
}
}
Output:
$ ./d.exe a b c d e f
Try this:
DoSomething(10, new string[] {"One", "Two", "Three"});
You can construct it while passing it in like so:
DoSomething(10, new string[] { "One", "Two", "Three"});
제휴하지 않습니다 StackOverflow