构造函数的理解

来源:互联网 发布:帝国时代mac版下载 编辑:程序博客网 时间:2024/05/11 21:08

 

public partial class Override_Default : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        Child p 
= new Child("dsf");
        p.GetName();
        p.GetLike();

        Child p1 
= new Child();
    }


   
}

public class Parent
{
    
string name = "";
    
public Parent(string name)
    
{
        
this.name = name;
    }



    
//这个要注意
    public Parent()
    
{
        name 
= "candu";
    }



    
//virtual 在子类如果要重写的话,关键字为:override
    public virtual string GetName()
    
{
        
return name;
    }

    
//这个方法要在子类重写的话,关键为:new
    
//不用也可以。.net只会警告你。可能有危险。
    public string GetLike()
    
{
        
return "df";
    }

}


public class Child : Parent
{
    
string a;
    
public Child() //构造函数的调用顺序:Parent的无参构造函数Parent() ,再调用 Child()    
    {
        a 
= "echo";
    }


    
public Child(string name) //构造函数的调用顺序:Parent的无参构造函数Parent() ,再调用 Child(string name)      
    {
        a 
= name;
    }

    
//从上面看到当创建派生类的对象时,系统将会调用基类的构造函数和派生类的构造函数,构 造函数的执行次序是:先执行基类的构造函数,再执行派生类的构造函数。
    
//如果派生类的构造函数没有 base 指定基类的构造函数时,它会默认调用基类中无参的构造函数。Parent()

    
//-----------------
    public Child(string name)
        : 
base("dd")////构造函数的调用顺序:Parent的无参构造函数Parent(string name) ,再调用 Child(string name)     
    {
        a 
= name;
    }

    
public Child()
        : 
base("<none>")////构造函数的调用顺序:Parent的无参构造函数Parent(string name) ,再调用 Child()   
    {
        a 
= "echo";
    }

    
public override string GetName()
    
{

        
string name = "dfg;"//base.GetName();
        name = "i love" + name;
        
return name;
    }

   
    
public new string GetLike()
    
{
        
return "canduecho";
    }

}

静态构造函数

静态构造函数是实现对一个类进行初始化的方法成员。它一般用于对静态数据的初始化。静态构造函数不能有参数,不能有修饰符而且不能被调用,当类被加载时,类的静态构造函数自动被调用。如:

 using System.Data;
class Employee
{
    private static DataSet ds;
    static Employee()
    {
        ds = new DataSet(...);
    }
    ...
}

当创建派生类的对象时,系统将会调用基类的构造函数和派生类的构造函数,构 造函数的执行次序是:先执行基类的构造函数,再执行派生类的构造函数。如果派生类又有对象成员,则,先执行基类的构造函数,再执行成员对象类的构造函数,最后执行派生类的构造函数。

至于执行基类的什么构造函数,缺省情况下是执行基类的无参构造函数,如果要执行基类的有参构造函数,则必须在派生类构造函数的成员初始化表中指出。如:

 class A
{
    private int x;
    public A( ) { x = 0; }
    public A( int i ) { x = i; }
}

class B : A
{
    private int y;
    public B( ) { y = 0; }
    public B( int i ) { y = i; }
    public B( int i, int j ):A(i) { y = j; }
}

B b1 = new B(); //执行基类A的构造函数A(),再执行派生类的构造函数B()
B b2 = new B(1); //执行基类A的构造函数A(),再执行派生类的构造函数B(int)
B b3 = new B(0,1); //执行执行基类A的构造函数A(int) ,再执行派生类的


构造函数B(int,int)
在这里构造函数的执行次序是一定要分析清楚的。另外,如果基类A中没有提供无参构造函数public A( )

 { x = 0; },则在派生类的所有构造函数成员初始化表中必须指出基类A的有参构造函数A(i),如下所示:

 class A
{
    private int x;
    public A( int i ) { x = i; }
}

class B : A
{
    private int y;
    public B():A(i) { y = 0; }
    public B(int i):A(i) { y = i; }
    public B(int i, int j):A(i) { y = j; }
}

 例如:


原创粉丝点击