성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; 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'>연산자 재정의(operator overloading)와 메서드 재정의(method overriding)의 다른 점 - 가상 함수 호출 여부</h1> <p> 영어의 override와 overload는 다른 의미이지만, 묘하게도 이것이 한글로 변환되었을 때 2가지 모두 '재정의'라고 번역되었는데요. 이 2가지 방식의 분명한 차이점이 하나 있다면 바로! 메서드 오버라이딩은 가상 함수 테이블(vtable: virtual function table)을 기반으로 동작한다는 점입니다.<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;' > using System; class Program { static void Main(string[] args) { Program p1 = new Program(); Program p2 = new Program(); <span style='color: blue; font-weight: bold'>bool result1 = p1 == p2;</span> } <span style='color: blue; font-weight: bold'> public static bool operator ==(Program objA, Program objB) { if (System.Object.ReferenceEquals(objA, objB)) { return true; } if (((object)objA == null) || ((object)objB == null)) { return false; } return objA.Equals(objB); }</span> public static bool operator !=(Program objA, Program objB) { return !(objA == objB); } } </pre> <br /> 'operator ==' 메서드를 재정의하고 있는데, == 메서드 내부에 정지점(BP: Breakpoint)를 걸고 F5 디버깅으로 실행해 보면 'bool result1 = p1 == p2;' 코드 실행 시 '==' 메서드 내부에 진입하는 것을 확인할 수 있습니다. (또는, 그냥 Console.WriteLine 코드를 넣어 실행 여부를 판단하면 되겠지요.)<br /> <br /> 하지만, Program 인스턴스가 아닌 object로 형변환해서 비교를 해보면 어떻게 될까요?<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) { Program p1 = new Program(); Program p2 = new Program(); bool result1 = p1 == p2; <span style='color: blue; font-weight: bold'>object po1 = p1; object po2 = p2; bool result2 = po1 == po2;</span> } </pre> <br /> 두번째인 'po1 == po2' 비교 연산 수행 시에는 정지점이 걸리지 않게 됩니다. 왜냐하면, 재정의한 'operator ==' 연산자는 가상 함수 테이블을 이용한 구현이 아닌, 정적 함수 호출에 해당하므로 가상(virtual) 함수 호출이 발생하지 않기 때문입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 좀 더 깊게 들어가 볼까요? ^^<br /> <br /> 연산자를 사용하는 경우 C# 컴파일러는 재정의 유무에 따라 다른 IL 코드를 내놓습니다. 연산자가 재정의되지 않은 경우, 가령 System.Object는 'operator =='에 대한 정의를 갖고 있지 않습니다. 그럴 때 C# 컴파일러는 ceq라는 IL 코드를 사용해 비교 연산 작업을 수행하도록 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > OpCodes.Ceq Field ; <a target='tab' href='https://docs.microsoft.com/ko-kr/dotnet/api/system.reflection.emit.opcodes.ceq'>https://docs.microsoft.com/ko-kr/dotnet/api/system.reflection.emit.opcodes.ceq</a> </pre> <br /> 하지만, '==' 연산자의 피연산자 타입이 'operator =='를 재정의하고 있다면 그 함수를 호출하는 코드를 IL로 출력해 줍니다. 실제로 이 글의 예제를 IL 코드로 번역해 보면 Program 타입과 System.Object 타입에 따른 '==' 연산자의 대응 방식을 확인할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 2 .locals init ( [0] class Program program, [1] class Program program2, [2] bool flag, [3] object obj2, [4] object obj3, [5] bool flag2) L_0000: nop L_0001: newobj instance void Program::.ctor() L_0006: stloc.0 L_0007: newobj instance void Program::.ctor() L_000c: stloc.1 L_000d: ldloc.0 L_000e: ldloc.1 <span style='color: blue; font-weight: bold'>L_000f: call bool Program::op_Equality(class Program, class Program)</span> // 피연산자가 Program 타입인 경우 L_0014: stloc.2 L_0015: ldloc.0 L_0016: stloc.3 L_0017: ldloc.1 L_0018: stloc.s obj3 L_001a: ldloc.3 L_001b: ldloc.s obj3 <span style='color: blue; font-weight: bold'>L_001d: ceq</span> // 피연산자가 System.Object인 경우 L_001f: stloc.s flag2 L_0021: ret } </pre> <br /> <hr style='width: 50%' /><br /> <br /> 따라서, 주의할 점을 하나 정리해 보면?<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;' > using System; class Program { public int Key; static void Main(string[] args) { DerivedProgram pdp1 = new DerivedProgram <span style='color: blue; font-weight: bold'>{ Key = 5, Key2 = 6 };</span> DerivedProgram pdp2 = new DerivedProgram <span style='color: blue; font-weight: bold'>{ Key = 5, Key2 = 7 };</span> bool result3 = pdp1 == pdp2; // Key, Key2 필드 2개 모두를 비교하기 때문에 false를 반환하지만! Program pp3 = pdp1; Program pp4 = pdp2; bool result4 = pp3 == pp4; // Key 필드 하나만 비교하므로 true를 반환 } public static bool operator ==(Program objA, Program objB) { return <span style='color: blue; font-weight: bold'>objA.Key == objB.Key</span>; // Key 필드 하나만 비교 } public static bool operator !=(Program objA, Program objB) { return !(objA == objB); } } class DerivedProgram : Program { public static bool operator ==(DerivedProgram objA, DerivedProgram objB) { return <span style='color: blue; font-weight: bold'>(objA.Key == objB.Key) && (objA.Key2 == objB.Key2)</span>; // Key, Key2 필드 2개 모두를 비교 } public static bool operator !=(DerivedProgram objA, DerivedProgram objB) { return !(objA == objB); } } </pre> <br /> 이 점에 대해 여러분들은 어떻게 생각하세요? 왠지, 연산자 재정의도 가상 함수 호출 기반으로 해야 하는 게 당연하지 않을까요?<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
4733
(왼쪽의 숫자를 입력해야 합니다.)