성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달</h1> <p> 간혹 메서드의 매개변수를 잘못 이해하고 계신 분들이 있는데요, 문법이 "메서드"라는 것에 엮여 있어 그런 것인지 혼란을 느끼는 듯합니다.<br /> <br /> 사실 간단하게 따져보면, 매개변수를 그냥 일반적인 지역 변수와 (기술적으로 복사 과정은 같기 때문에) 동일하게 생각해도 무방합니다. 예를 들어, 다음과 같은 메서드 호출을 볼까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal class Program { static void Main(string[] args) { int k = 5; Test(<span style='color: blue; font-weight: bold'>k</span>); } static void Test(<span style='color: blue; font-weight: bold'>int i</span>) { Console.WriteLine(i); } } </pre> <br /> 인자 k를 Test 메서드의 매개변수 i에 전달하고 있는데요, 이것을 다음과 같이 일반적인 변수 대입으로 펼치셔도 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal class Program { static void Main(string[] args) { int k = 5; Test(k); { <span style='color: blue; font-weight: bold'>int i = k;</span> Console.WriteLine(i); } } } </pre> <br /> 즉, 매개변수로 값이 복사되는 것과 저렇게 지역 변수로 값이 복사되는 것은 같은 동작입니다. 자, 그럼 이에 기반해서 문제를 풀어볼까요? ^^ <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal class Program { static void Main(string[] args) { <span style='color: blue; font-weight: bold'>MyClass instance = new MyClass { Id = 10 };</span> <span style='color: blue; font-weight: bold'>Test(instance); // 출력 결과: 10</span> System.Console.WriteLine(instance.Id); } static void Test(<span style='color: blue; font-weight: bold'>MyClass parameter</span>) { <span style='color: blue; font-weight: bold'>parameter = new MyClass { Id = 20 };</span> } } class MyClass { public int Id { get; set; } } </pre> <br /> 위의 코드는 instance를 넘겨받은 Test 메서드의 parameter에 다시 new를 할당했습니다. 간혹, class가 참조 타입이라는 이유로 저런 경우 instance 변수도 바뀌어야 한다고 여기는 분들이 있는데요, 위의 것을 이전에 설명한 지역 변수로 다시 풀어서 보면 왜 그렇게 될 수 없는지 쉽게 파악할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal class Program { static void Main(string[] args) { var instance = new MyClass { Id = 10 }; { <span style='color: blue; font-weight: bold'>MyClass parameter = instance; parameter = new MyClass { Id = 20 };</span> } System.Console.WriteLine(instance.Id); // 출력 결과: 10 } } class MyClass { public int Id { get; set; } } </pre> <br /> 위의 코드를 보면, parameter에 new로 새롭게 인스턴스를 대입한 것이 기존의 instance 변수에 영향을 미치지 못한다는 것을 쉽게 알 수 있습니다.<br /> <br /> 만약 넘긴 측의 인스턴스도 바꾸고 싶다면 다들 아시는 것처럼 매개변수에 ref를 적용하면 되는데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static void Main(string[] args) { MyClass instance = new MyClass { Id = 10 }; Test(<span style='color: blue; font-weight: bold'>ref</span> instance); System.Console.WriteLine(instance.Id); // 출력 결과: 20 } static void Test(<span style='color: blue; font-weight: bold'>ref</span> MyClass parameter) { <span style='color: blue; font-weight: bold'>parameter = new MyClass { Id = 20 };</span> } </pre> <br /> 마찬가지로 지역 변수를 이용해 위의 메서드 호출을 풀어보면 직관적으로 이해할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > internal class Program { static void Main(string[] args) { MyClass instance = new MyClass { Id = 10 }; { <span style='color: blue; font-weight: bold'>ref</span> MyClass parameter = <span style='color: blue; font-weight: bold'>ref</span> instance; parameter = new MyClass { Id = 20 }; } System.Console.WriteLine(instance.Id); // 출력 결과: 20 } } </pre> <br /> 대충 어떤 의미인지 아시겠죠? ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1199
(왼쪽의 숫자를 입력해야 합니다.)