sealed 类

sealed 修饰符可以应用于类、实例方法和属性。密封类不能被继承。密封方法会重写基类中的方法,但其本身不能在任何派生类中进一步重写。当应用于方法或属性时,sealed 修饰符必须始终与 override(C# 参考) 一起使用。

 

将密封类用作基类或将 abstract 修饰符与密封类一起使用是错误的。

结构是隐式密封的;因此它们不能被继承。

 

ContractedBlock.gif ExpandedBlockStart.gif Code
 1namespace Internal
 2ExpandedBlockStart.gifContractedBlock.gif{
 3    public class Animal
 4ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 5
 6        internal string strInternal = "china";
 7        public string strPublic;
 8        internal protected string strInternalProtected = null;
 9
10    }

11
12    public class Person
13ExpandedSubBlockStart.gifContractedSubBlock.gif    {
14        public string str = new Animal().strInternal;
15    }

16
17
18    public class A
19ExpandedSubBlockStart.gifContractedSubBlock.gif    {
20        public virtual void F()
21ExpandedSubBlockStart.gifContractedSubBlock.gif        {
22            Console.WriteLine("A.F");
23        }

24        public virtual void G()
25ExpandedSubBlockStart.gifContractedSubBlock.gif        {
26            Console.WriteLine("A.G");
27        }

28
29    }

30
31    public class B : A
32ExpandedSubBlockStart.gifContractedSubBlock.gif    {
33ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//*密封*/
34        public sealed override void F()
35ExpandedSubBlockStart.gifContractedSubBlock.gif        {
36            Console.WriteLine("B.F");
37        }

38
39        public override void G()
40ExpandedSubBlockStart.gifContractedSubBlock.gif        {
41            Console.WriteLine("B.G");
42        }

43    }

44
45ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*C 类只能继承 B 类没有密封的类 */
46    public  class C:B
47ExpandedSubBlockStart.gifContractedSubBlock.gif    {
48
49        public override void G()
50ExpandedSubBlockStart.gifContractedSubBlock.gif        {
51            Console.WriteLine("C.B");
52        }

53    }

54
55
56
57
58   public  class Program
59ExpandedSubBlockStart.gifContractedSubBlock.gif    {
60        static void Main(string[] args)
61ExpandedSubBlockStart.gifContractedSubBlock.gif        {
62
63            new A().F();
64            new A().G();
65            new B().F();
66            new B().G();
67            new C().F();
68            new C().G();
69        }

70    }

71}

 

转载于:https://www.cnblogs.com/liuyong/archive/2009/06/10/1498348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值