C#
C#-메소드와 파라미터
Jcon
2022. 8. 17. 21:46
2018. 5. 13
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
using System;
namespace CSharp_Console
{
/*
* 메소드와 파라미터
* 메소드 : 멤버 함수
* 파라미터 : 매개변수
*/
class Program
{
static void Add(int x)
{
x++;
}
static int Add(int x,int y)
{
return x + y;
}
static void rAdd(ref int x)
{
x++;
}
static void oAdd(out int x)
{
//out으로 받은 매개변수는 메소드 내에서 초기화를 하고
//사용해야 한다.
x = 1;
x++;
}
static int AddList(params int[] v)
{
int total = 0;
for (int i = 0; i < v.Length; i++)
{
total = total + v[i];
}
return total;
}
static void Func(string s, int i)
{
}
public static void Main()
{
int x = 0;
//※값에 의한 전달( pass by value )
// -원래 변수에 영향을 주지 않는다.
Add(x);
Console.WriteLine(x);
//※참조에 의한 전달( pass by reference )
// -ref키워드를 사용한다.
// -메소드 내에서 값이 변하면 원래 변수도 변한다.
// -반드시 초기화된 변수를 사용해야 한다.
rAdd(ref x);
Console.WriteLine(x);
//※out파라미터
// -out키워드를 사용한다.
// -초기화 되지 않는 변수를 사용해도 된다는 점을 제외하면
// 참조에 의한 전달과 동일하다.
int y;
oAdd(out y);
Console.WriteLine(y);
//※메소드 오버로딩
// -같은 이름이라도 여러 함수구현이 가능하다.
Add(1, 3);
//※가변길이 매개변수
// -pass by value로 값이 넘어간다.
AddList(1,2,3);
AddList(new int[] { 1, 2, 3, 4 });
//※명명된 매개 변수
// -순서에 상관없이 명시된 변수 이름에 값을 할당할 수 있다.
Func(i: 1, s: "Hello");
}
}
}
|
cs |