C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# 密封

C# Sealed

C#ealed 关键字对类和方法应用限制。如果创建密封类,则无法派生它。如果你创建了一个密封的方法,它就不能被覆盖。
注意: 结构是隐式密封的,因此它们不能被继承。

C# 密封类

C# 密封类不能被任何类派生。让我们看一个 C# 中密封类的例子。
using System;
sealed public class Animal{
    public void eat() { Console.WriteLine("eating..."); }
}
public class Dog: Animal
{
    public void bark() { Console.WriteLine("barking..."); }
}
public class TestSealed
{
    public static void Main()
    {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}
输出:
Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'

C# 密封方法

C# 中的密封方法不能被进一步覆盖。必须与方法中的override关键字一起使用。
让我们看一个C#中密封方法的例子。
using System;
public class Animal{
    public virtual void eat() { Console.WriteLine("eating..."); }
    public virtual void run() { Console.WriteLine("running..."); }
}
public class Dog: Animal
{
    public override void eat() { Console.WriteLine("eating bread..."); }
    public sealed override void run() { 
    Console.WriteLine("running very fast..."); 
    }
}
public class BabyDog : Dog
{
    public override void eat() { Console.WriteLine("eating biscuits..."); }
    public override void run() { Console.WriteLine("running slowly..."); }
}
public class TestSealed
{
    public static void Main()
    {
        BabyDog d = new BabyDog();
        d.eat();
        d.run();
    }
}
输出:
Compile Time Error: 'BabyDog.run()': cannot override inherited member 'Dog.run()' because it is sealed
注意: 局部变量不能被密封。
using System;
public class TestSealed
{
    public static void Main()
    {
        sealed int x = 10;
        x++;
        Console.WriteLine(x);
    }
}
输出:
Compile Time Error: Invalid expression term 'sealed'
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4