1 // property_hiding.cs
2 // Property hiding
3 using System;
4 public class BaseClass
5 {
6 private string name;
7 public string Name
8 {
9 get
10 {
11 return name;
12 }
13 set
14 {
15 name = value;
16 }
17 }
18 }
19
20 public class DerivedClass : BaseClass
21 {
22 private string name;
23 public new string Name // Notice the use of the new modifier
24 {
25 get
26 {
27 return name;
28 }
29 set
30 {
31 name = value;
32 }
33 }
34 }
35
36 public class MainClass
37 {
38 public static void Main()
39 {
40 DerivedClass d1 = new DerivedClass();
41 d1.Name = "John"; // Derived class property
42 Console.WriteLine("Name in the derived class is: {0}",d1.Name);
43 ((BaseClass)d1).Name = "Mary"; // Base class property
44 Console.WriteLine("Name in the base class is: {0}",
45 ((BaseClass)d1).Name);
46 }
47 }
请发表评论