[英]Static Class vs Protected Constructor
static
類不需要實例來訪問其成員。 static
類不能有實例成員(例如public int MyNumber;
在靜態類上是不允許的,因為靜態類只允許靜態成員)。 但是,非靜態類中允許使用實例成員和靜態成員。 具有protected
構造函數的類只能有一個由它自己創建的實例或從它繼承的東西。
public class Program
{
protected Program()
{
// Do something.
}
public static Program Create()
{
// 100% Allowed.
return new Program();
}
public void DoSomething()
{
}
}
public static class AnotherClass
{
public static Program CreateProgram()
{
// Not allowed since Program's constructor is protected.
return new Program();
}
}
public class SubProgram : Program
{
protected SubProgram()
{
// Calls Program() then SubProgram().
}
public new static Program Create()
{
// return new Program(); // We would need to move the SubProgram class INSIDE the Program class in order for this line to work.
return new SubProgram();
}
}
Program.Create(); // Can be called since Create is public and static function.
Program.DoSomething() // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething(); // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram(); // Can't be called since Program's constructor is protected.
SubProgram.Create(); // Can be called since SubProgram inherits from Program.
至於性能,這種區別實際上與性能沒有太大關系。
您可能在類中只有靜態成員,並且代碼分析器假定您的意圖是無法創建類的實例,因此它要求您將類設為靜態
public static class Program {
//...static members
}
或放置一個受保護/私有的構造函數
public class Program {
protected Program { //OR private
}
//...static members
}
以防止該類的實例被初始化。
靜態類與非靜態類基本相同,但有一個區別:靜態類不能被實例化。
受保護的構造函數意味着只有派生類才能調用構造函數
並且私有構造函數不允許任何其他類使用私有構造函數初始化該類
實例化類類型時會調用靜態構造函數。 在創建類的實例時調用受保護的構造函數。 受保護部分意味着只有繼承該類的類才能調用它。
靜態構造函數:類類型實例化時調用一次,用於初始化靜態成員。 不創建類的實例。
受保護的構造函數:只能由類或繼承它的類調用的構造函數。
對此的最佳實踐是,如果您只希望繼承的類能夠創建您的類的實例,則您應該有一個用於初始化靜態成員的靜態構造函數和一個受保護的構造函數。 你可以兩者兼得。
public class MyClass
{
static readonly long _someStaticMember;
private bool _param;
static MyClass()
{
//Do Some Logic
_someStaticMember = SomeValueCalculated;
}
protected MyClass(bool param)
{
_param = param;
}
}
public class ChildClass: MyClass
{
public ChildClass(bool param) : base(param);
}
public class NotChildClass
{
public MyClass someObject = new MyClass(true); //Will Fail
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.