执行命令的原因 [英] Reason for Order of Execution
问题描述
public class child:parent
{
public child()
{
System.Windows.Forms.MessageBox.Show("child ns");
}
static child()
{
System.Windows.Forms.MessageBox.Show("child s");
}
}
public class parent
{
public parent()
{
System.Windows.Forms.MessageBox.Show("parent ns");
}
static parent()
{
System.Windows.Forms.MessageBox.Show("parent s");
}
}
我有这段代码,当我将其作为子类的对象时...构造函数的执行顺序为子静态,父静态,父非静态和子非静态...我想知道的就是这个原因. ..
谢谢...
I have this code and when i make object of the child class... The order of execution of constructor is child static,parent static,parent non static and child non static... All i want to know is the reason for this...
Thanks...
推荐答案
静态必须位于非静态之前-否则非静态构造函数将无法依赖(甚至无法访问!)该类的静态元素.因此,所有静态构造都必须先于所有非静态构造.
子级构造必须在非静态类中跟随父级,以便子级实例可以依赖父级属性.实际上,将首先调用子级的构造函数-这会在执行任何子级代码之前触发父级构造函数.
唯一看起来很奇怪的是子优先静态,实际上遵循与公共相同的顺序:子构造优先,但是第一次需要父构造被调用-因此,如果您稍稍更改代码,则: br/>
Static has to precede non-static - otherwise the non-static constructor could not rely on (or even access!) static elements of the class. So all static construction needs to precede all non-static.
Child construction must follow parent in non-static classes, so that child instances can rely on parent properties. In actual fact, the constructor for the child is called first - this triggers the parent constructor before any child code is executed.
The only one which looks odd is the child-first static, which is actually following the same order as the public: child constructor first, but the parent constructor is called the first time it is needed - so if you change your code slightly:
public class child : parent
{
public child()
{
Console.WriteLine("child ns");
}
static child()
{
Console.WriteLine("child s");
X = "goodbye";
Console.WriteLine("child s end");
}
}
public class parent
{
public static string X = "hello";
public parent()
{
Console.WriteLine("parent ns");
}
static parent()
{
Console.WriteLine("parent s");
}
您将获得:
You will get:
child s
parent s
child s end
parent ns
child ns
,因为当子引用父静态属性时,将调用父静态构造函数;如果在此之前不需要,则在子构造函数的末尾调用ns.请记住,静态构造函数被调用一次,这是第一次引用静态属性或方法.
[edit]错别字:公开"而不是父母"和备用"the"-OriginalGriff [/edit]
Because the parent static constructor is called when the child references a parent static property, or at the end of the child constructor if it hasn''t been needed before then. Remember, Static constructors are called once, the first time a static property or method is referenced.
[edit]Typo: "public" instead of "parent" and a spare "the" - OriginalGriff[/edit]
这篇关于执行命令的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!