主要来看下以下代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyClass
{
class A
{
public A()
{
Console.WriteLine( " 我是类A的构造器 " );
}
public A( int i)
{
Console.WriteLine( " 我在A这里呢 " );
}
}
class B:A // B为A的子类
{
public B()
{
Console.WriteLine( " 我是类B的构造器 " );
}
public B( int i)
{
Console.WriteLine( " 我在B这里呢 " );
}
}
class Program
{
static void Main( string [] args)
{
B b = new B( 100 );
}
}
}
得到的结果是:
我是类A的构造器
我在B这里呢
从得到的结果可以看出,子类创建对象的时候,先调用父类的默认构造函数,然后子类再调用自己相应的构造函数。
如果有人想要声明的对象使用特定的构造函数,那么有什么办法呢?
在这里继续介绍一个base关键字
看下面的代码:
using
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyClass
{
class A
{
public A()
{
Console.WriteLine( " 我是类A的构造器 " );
}
public A( int i)
{
Console.WriteLine( " 我在A这里呢 " );
}
}
class B:A // B为A的子类
{
public B()
{
Console.WriteLine( " 我是类B的构造器 " );
}
public B( int i): base (i) // 注意base这个关键字
{
Console.WriteLine( " 我在B这里呢 " );
}
}
class Program
{
static void Main( string [] args)
{
B b = new B( 100 );
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyClass
{
class A
{
public A()
{
Console.WriteLine( " 我是类A的构造器 " );
}
public A( int i)
{
Console.WriteLine( " 我在A这里呢 " );
}
}
class B:A // B为A的子类
{
public B()
{
Console.WriteLine( " 我是类B的构造器 " );
}
public B( int i): base (i) // 注意base这个关键字
{
Console.WriteLine( " 我在B这里呢 " );
}
}
class Program
{
static void Main( string [] args)
{
B b = new B( 100 );
}
}
}
那么此时的结果为:
我在A这里呢
我在B这里呢
貌似由一个静态构造函数,他的作用是对静态成员进行初始化。