![](/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.