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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值