DEV Community

Cover image for C# - Sealed modifier
FakeStandard
FakeStandard

Posted on • Edited on

1

C# - Sealed modifier

今天想記錄 sealed (密封)修飾詞,它的定義很簡單,當你將 sealed 應用到類別時,sealed 修飾詞會防止其他類別繼承該類別,該類別則可繼承其它非 sealed 的類別

例如 Manager 類別使用 sealed 修飾詞,Manager 類別可繼承 Employee 類別,Employee 類別不可繼承 Manager,當然,任何類別都不可繼承 Manager

class Employee { }

sealed class Manager : Employee { }
Enter fullscreen mode Exit fullscreen mode

所以使用 sealed 修飾詞的類別不會有子類別,也不適合作為父類別使用,該類別也不可為抽象類別,因為 abstract 類別提供可實作的方法或屬性,其他子類別必須繼承 abstract 類別進行實作,所以當你將 sealedabstract 一起使用時會產生錯誤

pic-007

上圖錯誤清楚表示抽象類型不可以是密封或是靜態

sealed 也可以使用在可覆寫父類別中的虛擬方法或屬性,該類別允許其他類別繼承,但可防止他們覆寫特定的虛擬方法或屬性

class X
{
    protected virtual void M1() { }
    protected virtual void M2() { }
}

class Y : X
{
    // sealed 可使用於可覆寫方法
    protected sealed override void M1() { }
    protected override void M2() { }
}

class Z : Y
{
    // 此時無法覆寫密封方法
    //protected override void M1() { }
    protected override void M2() { }
}
Enter fullscreen mode Exit fullscreen mode

由於 Y 類別覆寫了 M1 方法並設置為 sealed ,所以當 Z 類別繼承 Y 類別時,Z 類別將無法覆寫 M1 方法,如果強制覆寫則會產生錯誤

pic-008

需要特別注意的地方:不是所有方法都可做為密封方法,要作為密封方法的話,必須覆寫父類別的虛擬方法並實作該方法,所以在密封方法中 sealedoverride 修飾詞會同時使用

Reference

sealed


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.


Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay