![](/img/trans.png)
[英]Objects in derived class reference base class in database, instead of derived class
[英]Derived Class instantiates 2 objects of BASE Class
我有一個基本的查詢。 我有一個派生的 class 是空的。 我注意到當我運行下面粘貼的一段代碼(在 Linqpad 中運行)時,我最終得到了 BASE Class 的 4 個對象。 我的理解是,當我們實例化派生的 class object 時,在沒有自己的構造函數的情況下,將調用 BASE Class 構造函數,導致派生 Class 構造函數的 1 個實例。
void Main()
{
NestedS n1 = new NestedS();
NestedS n2 = new NestedS();
NestedS n3 = new NestedS();
}
public class Base1
{
private static readonly Base1 instance = new Base1();
private static int numInstance = 0;
private readonly object lock1 = new object();
public Base1()
{
lock(lock1)
{
numInstance.Dump("before");
numInstance++;
numInstance.Dump("here");
}
}
}
public class NestedS : Base1{
}
該代碼產生了 4 個派生的 class 實例。 有人可以向我解釋其背后的原因嗎?
更新:對不起,在這里改寫我的查詢,同時粘貼 output。 從 output 開始,numInstance 應該在創建第二個實例之前已經初始化為 1,但在創建第二個實例時它仍然是 0:
before
0
here
1
before
0
here
1
before
1
here
2
before
2
here
3 ```
您令人驚訝的 output 的原因在於
private static readonly Base1 instance = new Base1();
private static int numInstance = 0;
語言標准說明了字段初始值設定項( https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#variable-initializers )(強調我的)
[...] when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order
因此,您的代碼首先創建instance
,將numInstances
設置為 1 ,然后執行行numInstance = 0;
將字段“重置”為0
。
將聲明的順序更改為
private static int numInstance = 0;
private static readonly Base1 instance = new Base1();
產生您期望的結果,因為numInstances
在您構造第一個實例之前首先被初始化為 0(技術上兩次)。 或者,您也可以從numInstances
中刪除初始化程序,因為int
的默認值無論如何都是 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.