성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
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# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)</h1> <p> 아래의 내용에 이어,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12330'>https://www.sysnet.pe.kr/2/0/12330</a> </pre> <br /> 덧글에서 또다시 의문을 제기했는데,<br /> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> 그런데 아래 내용에서 another에 value+1의 값을 넣었으면 연산 순서에 따라 연산이 된 value+1의 값이 another라는 instance에 들어가야 하는데 그렇지 않고 왜 반환되는 값은 value인 것인지 이해가 가지 않습니다.<br /> <br /> public static Integer operator ++(Integer instance)<br /> {<br /> Integer another = new Integer(instance._value + 1);<br /> return another;<br /> }<br /> </div><br /> <br /> 어찌 보면 신기할 수 있지만, 사실 일반적인 전위/후위 원칙과 별반 다르지 않습니다. 이미 기존에도 설명했지만, 동일한 ++의 코드임에도 전/후위 표기에 따라 C# 컴파일러는 Increment/Decrement 연산자의 사용 코드를 다음과 같이 풀어서 번역합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int n = 5; int value = ++ n; ==> ++를 사용하는 측에서 다음과 같이 코드 번역 int n = 5; n = n + 1; // 값을 증가시키고, int value = n; // 이후에 대입 </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int n = 5; int value = n ++; ==> ++를 사용하는 측에서 다음과 같이 코드 번역 int n = 5; int value = n; // 값을 먼저 대입하고, n = n + 1; // 이후에 증가 </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;' > { Integer n = new Integer(5); Integer value = n++; } ==> { Integer n = new Integer(5); Integer temp = Integer.operator ++(n); Integer value = n; n = temp; } { Integer n = new Integer(5); Integer value = ++n; } ==> { Integer n = new Integer(5); Integer value = Integer.operator ++(n); n = value; } </pre> <br /> 실제로 저렇게 번역이 되는지 확인하고 싶다면 IL 코드를 보면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .locals init ( [0] class Integer n, [1] class Integer 'value', [2] class Integer n, [3] class Integer 'value' ) /* 0x0000025C 00 */ IL_0000: nop /* 0x0000025D 00 */ IL_0001: nop /* 0x0000025E 1B */ IL_0002: ldc.i4.5 /* 0x0000025F 7303000006 */ IL_0003: newobj instance void Integer::.ctor(int32) /* 0x00000264 0A */ IL_0008: stloc.0 <span style='color: blue; font-weight: bold'>/* 0x00000265 06 */ IL_0009: ldloc.0 /* 0x00000266 25 */ IL_000A: dup /* 0x00000267 2804000006 */ IL_000B: call class Integer Integer::op_Increment(class Integer) /* 0x0000026C 0A */ IL_0010: stloc.0 /* 0x0000026D 0B */ IL_0011: stloc.1 </span>/* 0x0000026E 07 */ IL_0012: ldloc.1 /* 0x0000026F 280F00000A */ IL_0013: call void [mscorlib]System.Console::WriteLine(object) /* 0x00000274 00 */ IL_0018: nop /* 0x00000275 00 */ IL_0019: nop /* 0x00000276 00 */ IL_001A: nop /* 0x00000277 1B */ IL_001B: ldc.i4.5 /* 0x00000278 7303000006 */ IL_001C: newobj instance void Integer::.ctor(int32) /* 0x0000027D 0C */ IL_0021: stloc.2 <span style='color: blue; font-weight: bold'>/* 0x0000027E 08 */ IL_0022: ldloc.2 /* 0x0000027F 2804000006 */ IL_0023: call class Integer Integer::op_Increment(class Integer) /* 0x00000284 25 */ IL_0028: dup /* 0x00000285 0C */ IL_0029: stloc.2 /* 0x00000286 0D */ IL_002A: stloc.3 </span>/* 0x00000287 09 */ IL_002B: ldloc.3 /* 0x00000288 280F00000A */ IL_002C: call void [mscorlib]System.Console::WriteLine(object) /* 0x0000028D 00 */ IL_0031: nop /* 0x0000028E 00 */ IL_0032: nop /* 0x0000028F 2A */ IL_0033: ret </pre> <br /> <hr style='width: 50%' /><br /> <br /> 답변을 하다 보니, 재미있는 점이 눈에 띕니다. 전위 연산자의 경우에는 상관없지만, 후위 연산자의 경우에는, (<a target='tab' href='https://www.sysnet.pe.kr/2/0/11131'>후위 연산자가 꽤나 문제</a>군요. ^^)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > { Integer n = new Integer(5); Integer value = ++n; } ==> { Integer n = new Integer(5); <span style='color: blue; font-weight: bold'>Integer value</span> = Integer.operator ++(n); <span style='color: blue; font-weight: bold'>n = value</span>; } </pre> <br /> 결국 같은 인스턴스가 n과 value에 들어가 참조 값이 같아집니다. 실제로 이를 다음의 코드로 테스트해볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > { Integer n = new Integer(5); Integer value = ++n; <span style='color: blue; font-weight: bold'>value.Increment()</span>; // <span style='color: blue; font-weight: bold'>value.Increment()</span>; // <span style='color: blue; font-weight: bold'>value의 값을 변경했지만,</span> <span style='color: blue; font-weight: bold'>value.Increment()</span>; // Console.WriteLine(<span style='color: blue; font-weight: bold'>value</span>); // <span style='color: blue; font-weight: bold'>출력 결과: 9</span> Console.WriteLine(<span style='color: blue; font-weight: bold'>n</span>); // <span style='color: blue; font-weight: bold'>출력 결과: 9</span> (n의 값도 함께 변경) } public class Integer { int _value; // ...[생략]... internal void Increment() { _value++; } } </pre> <br /> 이것은 일종의 side-effect 일 수 있는데, 이런 부분을 고려한다면 연산자 오버로딩을 포함한 타입은 가능한 class보다는 struct로 구현하는 것이 권장됩니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
4340
(왼쪽의 숫자를 입력해야 합니다.)