Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

게임 프로그래밍

[C#] params 가변인자 본문

프로그래밍/C#

[C#] params 가변인자

Junwe 2020. 3. 1. 06:10

1. params란?

 간단하게 매개변수의 개수 제한 없이 만드는 거라고 생각하면 된다.

 

2. 조건

params 키워드를 사용하면 가변 개수의 인수를 사용하는 메서드 매개 변수를 지정할 수 있습니다.

 

매개 변수 선언이나 지정된 형식의 인수 배열에 지정된 형식의 쉼표로 구분된 인수 목록을 보낼 수 있습니다. 인수를 보내지 않을 수도 있습니다. 인수를 보내지 않는 경우 params 목록의 길이는 0입니다.

메서드 선언에서 params 키워드 뒤에는 추가 매개 변수가 허용되지 않으며, params 키워드 하나만 메서드 선언에 사용할 수 있습니다.

params 매개 변수의 선언된 형식은 다음 예제와 같이 1차원 배열이어야 합니다. 그렇지 않으면 컴파일러 오류 CS0225가 발생합니다.

 

3. 사용 예제

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
 
    public static void UseParams2(params object[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
 
    static void Main()
    {
        // You can send a comma-separated list of arguments of the 
        // specified type.
        UseParams(1234);
        UseParams2(1'a'"test");
 
        // A params parameter accepts zero or more arguments.
        // The following calling statement displays only a blank line.
        UseParams2();
 
        // An array argument can be passed, as long as the array
        // type matches the parameter type of the method being called.
        int[] myIntArray = { 56789 };
        UseParams(myIntArray);
 
        object[] myObjArray = { 2'b'"test""again" };
        UseParams2(myObjArray);
 
        // The following call causes a compiler error because the object
        // array cannot be converted into an integer array.
        //UseParams(myObjArray);
 
        // The following call does not cause an error, but the entire 
        // integer array becomes the first element of the params array.
        UseParams2(myIntArray);
    }
}
/*
Output:
    1 2 3 4
    1 a test
           
    5 6 7 8 9
    2 b test again
    System.Int32[]
*/
cs

"," 로 구분해서 넣어줘도 되고, 배열로 넣어줘도 된다. 

매개변수를 여러개 넣어줘야하는 경우가 생기는데 그럴 때 좋을것 같다.

'프로그래밍 > C#' 카테고리의 다른 글

[C#] Enum 반복문  (0) 2020.03.02
[C#] is, as에 대해서  (0) 2020.03.01
[C#] CSV 파일 저장하기  (0) 2020.02.19
[c#] BinaryFormatter  (0) 2020.01.14
C# &&연산자 팁  (0) 2016.04.25
Comments