상속관계에 있는 클래스에서 메소드를 기존의 이름으로 재정의하고 싶을 때 override-virtual, new, 로컬메소드 등의 3가지 방법이 있는데 차이가 많이 햇갈릴때가 있다.
다음과 같은 예제 코드를 해보면 이해가 조금 더 쉽게 되지 않을까 생각한다.
(아래 예제는 Visual Studio Sample 폴더에 있는 예제입니다.)
1: //Copyright (C) Microsoft Corporation. All rights reserved.
2: 3: // versioning.cs
4: // CS0114 expected
5: public class MyBase
6: {7: public virtual string Meth1()
8: {9: return "MyBase-Meth1";
10: }11: public virtual string Meth2()
12: {13: return "MyBase-Meth2";
14: }15: public virtual string Meth3()
16: {17: return "MyBase-Meth3";
18: } 19: } 20: 21: class MyDerived : MyBase
22: {23: // Overrides the virtual method Meth1 using the override keyword:
24: public override string Meth1()
25: {26: return "MyDerived-Meth1";
27: }28: // Explicitly hide the virtual method Meth2 using the new
29: // keyword:
30: public new string Meth2()
31: {32: return "MyDerived-Meth2";
33: }34: // Because no keyword is specified in the following declaration
35: // a warning will be issued to alert the programmer that
36: // the method hides the inherited member MyBase.Meth3():
37: public string Meth3()
38: {39: return "MyDerived-Meth3";
40: } 41: 42: public static void Main()
43: {44: MyDerived mD = new MyDerived();
45: MyBase mB = (MyBase) mD; 46: 47: System.Console.WriteLine(mB.Meth1()); 48: System.Console.WriteLine(mB.Meth2()); 49: System.Console.WriteLine(mB.Meth3()); 50: } 51: } 52: 'Development > .NET' 카테고리의 다른 글
| 고품질 코드 작성 (0) | 2008.04.18 |
|---|---|
| Visual Studio Add-in CopySourceAsHtml (0) | 2008.04.15 |
| .NET C# Base64 Decode (0) | 2008.04.12 |
| MS Heros Happen here 세미나 자료 (0) | 2008.04.10 |
| Windows RSS Platform (0) | 2008.04.07 |