📜  C#sealed关键字

📅  最后修改于: 2020-10-31 03:17:59             🧑  作者: Mango

C#sealed关键字

C#sealed关键字对类和方法施加限制。如果创建sealed类,则不能派生它。如果创建sealed方法,则不能覆盖该方法。

注意:结构是隐式sealed的,因此无法继承。

C#sealed等级

C#sealed类不能由任何类派生。让我们看一下C#中的sealed类示例。

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#sealed方法

C#中的sealed方法无法进一步覆盖。它必须与method中的override关键字一起使用。

让我们看一下C#中的sealed方法示例。

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

注意:局部变量不能被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'