review——C# (5)屏蔽基类的成员

FROM P121

  虽然派生类不能删除它继承的任何成员,但可以用与基类成员名称相同的成员来屏蔽(mask)基类成员。

□要屏蔽一个继承的数据成员,需要声明一个新的相同类型的成员,并使用相同的名称。

□通过在派生类中声明新的带有相同签名的函数成员,可以隐藏or屏蔽继承的函数成员。

请记住,签名由名称和参数列表组成,不包括返回类型

□要让编译器知道你在故意屏蔽继承的成员,使用new修饰符。否则,程序可以成功编译,但编译器会警告你隐藏了一个继承的成员。

□也可以屏蔽静态成员

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace review
 8 {
 9     class class1
10     {
11         public string Field1 = "Field1";
12         public void Method1(string value)
13         {
14             Console.WriteLine("class1 {0}", value);
15         }
16     }
17     class class2 : class1
18     {
19         new public string Field1 = "Field2";
20         new public void Method1(string value)
21         {
22             Console.WriteLine("class2 {0}", value);
23             Console.WriteLine("class2 {0}", base.Field1);
24         }
25     }
26     class Program
27     {
28         static void Main(string[] args)
29         {
30             class2 tem = new class2();
31             tem.Method1(tem.Field1);
32             ((class1)tem).Method1(((class1)tem).Field1);
33             Console.Read();
34         }
35     }
36 }

输出结果:

class2 Field2

class2 Field1

class1 Field1

第二行的输出说明了,即使隐藏了继承自基类的一些字段、方法,也可以通过使用base. 来访问隐藏的继承成员。

对第三的说明为:

当对某个引用调用某个方法时,调用的是该引用所能看到的方法的实现。

对于第三行的输出,是从class1的引用类型来看tem,使用class1的引用类型来看Field1字段。因此会产生输出:class1 Field1

原文地址:https://www.cnblogs.com/quintessence/p/9099405.html