跳转至

密封类与静态类#

来源:D:\study\C#1\stu0727\密封类和静态类

密封类(sealed)#

使用 sealed 修饰的类不能被继承

// 密封类 — 禁止任何类继承它
sealed class Test
{
}
// class MyTest : Test  // ❌ 编译错误:Test 是密封类,不能被继承

静态类(static)#

使用 static 修饰的类不能被实例化,也不能被继承,且只能包含静态成员:

// 静态类 — 不能被 new,不能被继承,只能有静态成员
static class Tttt
{
    public static int Age { get; set; }
}

// class SubTttt : Tttt  // ❌ 编译错误:静态类不能被继承
// Tttt t = new Tttt();   // ❌ 编译错误:静态类不能被实例化

扩展方法#

静态类还有一个特殊用途:定义扩展方法,为已有类型添加新方法:

// 静态类中定义扩展方法
static class Fn
{
    // this 关键字在第一个参数前 → 表示这是 string 的扩展方法
    public static int My(this string s, string v)
    {
        return -1;
    }
}

// 使用扩展方法 — 像调用实例方法一样调用
string s = "abcd";
Console.WriteLine(s.IndexOf("c"));  // 内置方法
Console.WriteLine(s.My("f"));       // 扩展方法

密封类与抽象类的互斥#

类类型 能否被继承 能否实例化
abstract(抽象类) ✅ 设计用来被继承 ❌ 不能
sealed(密封类) ❌ 禁止被继承 ✅ 可以
static(静态类) ❌ 禁止被继承 ❌ 不能

抽象类和密封类不能同时使用(abstract sealed 矛盾)。



相关笔记#