[英]Static and Sealed class differences
有沒有在靜態類中實現的類? 方法:
static class ABC : Anyclass
是否有任何類可以在密封類和靜態類中繼承?
方法:
static class ABC : AClass {}
和
sealed class ABC : AClass {}
我可能在某種程度上是錯的嗎?
這可能會幫助您:
+--------------+---+-------------------------+------------------+---------------------+
| Class Type | | Can inherit from others | Can be inherited | Can be instantiated |
|--------------|---|-------------------------+------------------+---------------------+
| normal | : | YES | YES | YES |
| abstract | : | YES | YES | NO |
| sealed | : | YES | NO | YES |
| static | : | NO | NO | NO |
+--------------+---+-------------------------+------------------+---------------------+
簡單來說
靜態類
一個類可以聲明為靜態的,表明它只包含靜態成員。 無法使用 new 關鍵字創建靜態類的實例。 加載包含類的程序或命名空間時,.NET Framework 公共語言運行時 (CLR) 會自動加載靜態類。
密封類
密封類不能用作基類。 密封類主要用於防止派生。 因為它們永遠不能用作基類,所以一些運行時優化可以使調用密封類成員的速度稍快一些。
您可以讓sealed
類從另一個類繼承,但不能從sealed
類繼承:
sealed class MySealedClass : BaseClass // is ok
class MyOtherClass : MySealedClass // won't compile
static
類不能從其他類繼承。
您可以簡單地將它們區分為:
Sealed Class | Static Class
--------------------------|-------------------------
it can inherit From other | it cannot inherit From other
classes but cannot be | classes as well as cannot be
inherited | inherited
簡單的回答是密封類不能用作基類。
我試圖向您展示密封類是下面代碼中的派生類
public sealed class SealedClass : ClassBase
{
public override void Print()
{
base.Print();
}
}
另一個密封特性只能通過它的實例訪問。(你不能從它繼承)
class Program
{
static void Main(string[] args)
{
SealedClass objSeald = new SealedClass();
objSeald.Name = "Blah blah balh";
objSeald.Print();
}
}
public class BaseClassDemo
{
}
//Note
//A static class can be used as a convenient container for sets of
//methods that just operate on input parameters and do not have to
//get or set any internal instance fields.
//The advantage of using a static class is that the compiler can
//check to make sure that no instance members are accidentally
//added. The compiler will guarantee that instances of this class
//cannot be created.
//Static class 'static type' cannot derive from type 'type'. Static
//classes must derive from object.
public static class StaticClassDemo : BaseClassDemo //Error
public static class StaticClassDemo
{
//Static class must have static members
public static void Ram()
{
throw new NotImplementedException();
}
}
//Sealed class can inherit from the base class.
public sealed class SealedClassDemo : BaseClassDemo
{
}
//We can't derive from sealed class.
public class derivedClass:SealedClassDemo //Error
public partial class RandomClass2
{
//we can't create instance of static class.
StaticClassDemo demo = new StaticClassDemo() //Error
}
1 - 不,您不能實現靜態類。
2 - 不,您不能從靜態或密封類繼承
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.