C# - Seal关键字

C# - Seal关键字 首页 / C#入门教程 / C# - Seal关键字

C#Seal关键字对类和方法应用限制。如果创建Seal类,则无法派生它。如果创建Seal方法,则无法重写该方法。

C# Seal类

C# Seal类不能由任何类派生。让无涯教程看一个用C#编写的Seal类的示例。

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();


    }
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-sealed.html

来源:LearnFk无涯教程网

Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'

C#Seal方法

不能进一步重写C#中的Seal方法。它必须与方法中的Override关键字一起使用。

让无涯教程看一个用C#编写的Seal方法的示例。

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();
    }
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-sealed.html

来源:LearnFk无涯教程网

Compile Time Error: 'BabyDog.run()': cannot override inherited member 'Dog.run()' because it is sealed

Note: Local variables can't be sealed.

using System;
public class TestSealed
{
    public static void Main()
    {
        sealed int x = 10;
        x++;
        Console.WriteLine(x);
    }
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-sealed.html

来源:LearnFk无涯教程网

Compile Time Error: Invalid expression term 'sealed'

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

推荐系统三十六式 -〔刑无刀〕

Electron开发实战 -〔邓耀龙〕

微信小程序全栈开发实战 -〔李艺〕

To B市场品牌实战课 -〔曹林〕

全链路压测实战30讲 -〔高楼〕

网络排查案例课 -〔杨胜辉〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

大型Android系统重构实战 -〔黄俊彬〕

程序员职业规划手册 -〔雪梅〕

好记忆不如烂笔头。留下您的足迹吧 :)