- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑下面的代码。字段i
和j
在m
和n
之前初始化。我们知道父对象是在子对象之前创建的,但是在我的程序中,编译器在基类之前为子类的成员变量分配和初始化内存。这是为什么?
class X
{
private int m = 0;
private int n = 90;
public X() { }
}
class Y:X
{
private int i = 8;
private int j = 6;
public Y()
{ }
public static void Main(string []args)
{
Y y1 = new Y();
}
}
最佳答案
这在 Eric Lippert's blog 中有解释:
[...] an initialized readonly field is always observed in its initialized state, and we cannot make that guarantee unless we run all the initializers first, and then all of the constructor bodies.
不确定为什么这里提到readonly
,但是例如,这确保了以下场景,尽管很愚蠢,但可以工作:
1.
class Base
{
public Base()
{
if (this is Derived) (this as Derived).Go();
}
}
class Derived : Base
{
X x = new X();
public void Go()
{
x.DoSomething(); // !
}
}
2.
class Base
{
public Base()
{
Go();
}
public virtual Go() {}
}
class Derived : Base
{
X x = new X();
public override void Go()
{
x.DoSomething(); // !
}
}
此顺序在 C# Language Specification 中明确说明(17.10.2):
[...] constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.
关于c# - 为什么子类变量先于父类成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850323/
在我正在处理的应用程序上,onCreate 使用 startService() 启动一个服务,随后,该 Activity 在其 onStart 中调用 bindService(到同一服务)。问题是服务
这个问题已经有答案了: Problem joining tables where joined table needs to be ordered before grouping (2 个回答) 已关
上下文(虽然不重要),在 netfilter 模块中,我们使用如下结构: struct data { char mac[ETH_ALEN]; char in6_addr addr; }
Google Chrome 的页面性能审核建议将 CSS 导入放在 header 中的 JS 导入之前,以允许并行下载 CSS 和 JS 文件。 但是,我注意到这会导致 Firefox 在导航到另一个
这个问题已经有答案了: Results of printf() and system() are in the wrong order when output is redirected to a f
这个问题已经有答案了: Results of printf() and system() are in the wrong order when output is redirected to a f
我想获得按 project_id 排序的独特帖子基本上,如果有重复的帖子,我想要其中 project_id 的帖子不为空。 有什么办法可以得到这个吗? 此代码返回唯一的帖子,但它们不是按 projec
我是一名优秀的程序员,十分优秀!