本文概述
C#密封关键字对类和方法施加限制。如果创建密封类,则不能派生它。如果创建密封方法,则不能覆盖该方法。
注意:结构是隐式密封的,因此无法继承。
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#中的密封方法无法进一步覆盖。它必须与method中的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'
评论前必须登录!
注册