Calling order of base and derived constructors
I have a base class and derived class. If I'm creating an object of开发者_如何学JAVA the derived class, which constructor will be taken first: the base constructor or the derived constructor?
The instance constructors are initialize in reverse order. The base constructor will be initialized first, then the derived constructor.
Take a look here http://www.csharp411.com/c-object-initialization/
There is a good overview of the order in which the object's fields and constructors are initialized:
- Derived static fields
- Derived static constructor
- Derived instance fields
- Base static fields
- Base static constructor
- Base instance fields
- Base instance constructor
- Derived instance constructor
Base constructor is called first. That's easy to verify:
class Program
{
class Base
{
public Base()
{
Console.WriteLine("base ctor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("derived ctor");
}
}
static void Main()
{
new Derived();
}
}
first called the base class
constructor
class Base
{
public Base()
{
Console.WriteLine("Base");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived");
}
}
class Program
{
static void Main()
{
Derived d = new Derived();
}
}
output will be
Base
Derived
Taking the question at face value (i.e. with no code), then, the base class constructor runs first. This way the base class can be initialised first - the derived class may depend on objects in the base class being initialised .
If there are two or more levels of inheritance then the least specialised constructor is called first.
First the base c'tor will run, and then derived one.
The base constructor will be called first.
try it:
public class MyBase
{
public MyBase()
{
Console.WriteLine("MyBase");
}
}
public class MyDerived : MyBase
{
public MyDerived():base()
{
Console.WriteLine("MyDerived");
}
}
Check this link too for details - http://www.csharp-station.com/Tutorials/lesson08.aspx
Assuming your code is like this:
class Foo
{
public Foo()
{}
}
class Bar : Foo
{
public Bar() : base()
{}
}
then calling the constructor of Bar
will run the constructor of Foo
first.
The base class constructor will be called first.
For example, if you have these classes:
public class A {
public A() {
Console.WriteLine("a");
}
}
public class B : A {
public B() {
Console.WriteLine("b");
}
}
If you create an instance of the class B
, it will first output "a", then "b".
The base class constructor will be processed first, followed by each derived constructor.
*edit added the following code * You can see this by creating a ClassOne object and using the debug "Step Into" on the following:
class BaseClass
{
public BaseClass(int num)
{
this.fieldNumber = num;
}
private int fieldNumber;
}
class ClassOne : BaseClass
{
public ClassOne(int num1, int num2): base(num1)
{
this.fieldNumber = num2;
}
private int fieldNumber;
}
精彩评论