성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
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# - 인터페이스의 메서드가 다형성을 제공할까요? (virtual일까요?)</h1> <p> 이 글을 쓰려니.. 참 부끄럽군요. ^^; 저는 여태껏 C#의 인터페이스 메서드는 기본적으로 virtual이라고 알고 있었습니다. 사실, 인터페이스의 IL 정의를 보면 virtual이라고 지정돼 있으며,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public <span style='color: blue; font-weight: bold'>interface</span> IMessage { <span style='color: blue; font-weight: bold'>void Write();</span> } /* IL 코드 .class interface public auto ansi abstract IMessage { .method public hidebysig newslot abstract <span style='color: blue; font-weight: bold'>virtual</span> instance void Write () cil managed { } } */ </pre> <br /> 클래스와 비교했을 때 당연히 일반 메서드는 virtual이 없고 virtual이 명시된 메서드에만 위에서 본 "virtual" 예약어가 정의됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public <span style='color: blue; font-weight: bold'>class</span> Test { <span style='color: blue; font-weight: bold'>public void Write() { }</span> <span style='color: blue; font-weight: bold'>public virtual void Log() { }</span> } .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig <span style='color: blue; font-weight: bold'>instance void Write</span> () cil managed { // ...[생략]... } .method public hidebysig newslot <span style='color: blue; font-weight: bold'>virtual instance</span> void Log () cil managed { // ...[생략]... } // ...[생략]... } </pre> <br /> 보는 바와 같이, 인터페이스에 정의된 메서드와 일반 클래스에 정의된 virtual 메서드의 차이점은,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .method public hidebysig newslot abstract virtual instance void Write () cil managed .method public hidebysig newslot virtual instance void Log () cil managed </pre> <br /> abstract의 차이점뿐입니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그런데 실제로 코딩을 해보면, 인터페이스의 메서드는 상속받은 클래스에서 구현한 경우 일반 메서드처럼 "virtual"이 누락된 것처럼 동작하고, 따라서 다형성조차도 제공되지 않습니다.<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; namespace ConsoleApp1 { class Program { static void Main(string[] args) { <span style='color: blue; font-weight: bold'>IMessage</span> msg = <span style='color: blue; font-weight: bold'>new UserMessage();</span> <span style='color: blue; font-weight: bold'>msg.Write(); // 출력 결과: Message.Write</span> } } } public interface IMessage { void Write(); } public class Message : IMessage { public void Write() { Console.WriteLine("Message.Write"); } } public class UserMessage : Message { // new를 지정하지 않으면 컴파일 경고 발생 // warning CS0108: 'UserMessage.Write()' hides inherited member 'Message.Write()'. Use the new keyword if hiding was intended. public <span style='color: blue; font-weight: bold'>new</span> void Write() { Console.WriteLine("UserMessage.Write"); } } </pre> <br /> 구현한 인터페이스 메서드에 다형성을 제공하려면 명시적으로 virtual 예약어를 (상속받은) 클래스 수준에서 제공해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > IMessage msg = new UserMessage(); msg.Write(); // 출력 결과: UserMessage.Write public class Message : IMessage { public <span style='color: blue; font-weight: bold'>virtual</span> void Write() { Console.WriteLine("Message.Write"); } } public class UserMessage : Message { public <span style='color: blue; font-weight: bold'>override</span> void Write() { Console.WriteLine("UserMessage.Write"); } } </pre> <br /> (만약, 인터페이스 메서드에 직접 virtual 예약어를 명시하면 "CS0501 'IMessage.Write()' must declare a body because it is not marked abstract, extern, or partial" 오류가 발생합니다.)<br /> <br /> <hr style='width: 50%' /><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;' > Message msg = new AdminMessage(); msg.Print(); // "Message.Print" UserMessage msg2 = new AdminMessage(); msg2.Print(); // "AdminMessage.Print" public interface IMessage { <span style='color: blue; font-weight: bold'>void Print();</span> } public class Message : IMessage { public <span style='color: blue; font-weight: bold'>void</span> Print() { Console.WriteLine("Message.Print"); } } public class UserMessage : Message { public <span style='color: blue; font-weight: bold'>new virtual void</span> Print() { Console.WriteLine("UserMessage.Print"); } } public class AdminMessage : UserMessage { public <span style='color: blue; font-weight: bold'>override void</span> Print() { Console.WriteLine("AdminMessage.Print"); } } </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;' > interface IAdd { int Add(int arg1, int arg2); } public class Adder : IAdd { public int Add(int arg1, int arg2) => arg1 + arg2; } </pre> <br /> 다형성이 없는 메서드가 구현된 클래스로 바꾸려고 하면 이번엔 구현 클래스에서 명시적인 new를 필요로 하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public <span style='color: blue; font-weight: bold'>class</span> IAdd { public int Add(int arg1, int arg2) => 0; } public class Adder : IAdd { public <span style='color: blue; font-weight: bold'>new</span> int Add(int arg1, int arg2) => arg1 + arg2; } </pre> <br /> 그렇다고 인터페이스처럼 동작하도록 만들기 위해 abstract로 바꾸려고 하면 아예 상속 구조 전체에서 virtual 메서드가 적용된 것이므로 차이가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public <span style='color: blue; font-weight: bold'>abstract class</span> IAdd { public <span style='color: blue; font-weight: bold'>abstract</span> int Add(int arg1, int arg2); } public class Adder : IAdd { public <span style='color: blue; font-weight: bold'>override</span> int Add(int arg1, int arg2) => arg1 + arg2; } </pre> <br /> 즉, 인터페이스는 참 이상한 정의라고 볼 수 있는데, 간단하게 정리하면 1레벨 수준의 상속에 대해서만 다형성을 제공하는 것입니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1844&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 어쨌든, 이것 때문에 또 <a target='tab' href='https://www.sysnet.pe.kr/2/0/12787'>책의 내용을 수정</a>해야만 했습니다. ^^;<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
3900
(왼쪽의 숫자를 입력해야 합니다.)