C#.NET中结构体与类的构造函数的异同

        在结构体与类中的构造函数大致的作用相同,但同时也存在不少的区别,而且这些区别相当重要。
        一、先看类中的构造函数

/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-26
 * Time: 12:30
 * 
 * 类的构造函数。
 * (1)当类中没有写构造函数时,实例化类的时候会默认调用父类System.Object的无参构造函数。
 * (2)当类中只写了带参的构造函数时,实例化类的时候只能调用这个重载的构造函数,而继续调用无参的构造函数会提示错误。
 
*/
using System ;
class constructA
{
    
public void output()
    {
        Console.WriteLine (
"success");
    }
}
class constructB
{
    
public constructB(int a)
    {
        Console.WriteLine (a);
    }
    
public void output()
    {
        Console.WriteLine (
"success");
    }
}
class test
{
    
static void Main()
    {
        constructA cA
=new constructA ();
        cA.output();
        
//        constructB cB=new constructB ();//调用错误,“constructB”方法没有采用“0”个参数的重载
//        cB.output ();
        
        constructB cB
=new constructB (5);
        cB.output ();
    }
}

二、接着看结构体中的构造函数

/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-26
 * Time: 12:44
 * 
 * 结构体的构造函数
 * (1)结构体中不能写无参的构造函数,只能写带参的构造函数,这同类的构造函数不一样。
 * (2)在结构体中只有带参的构造函数时,可以调用无参的构造函数来实例化结构体,这个同类也不一样。
 * 
 
*/

using System ;
struct constructC
{
//    constructC()//结构不能包含显式的无参数构造函数,这是结构体默认的构造函数,与类不同,这个不能重写。
//    {
//        Console.WriteLine ("fail");
//    }
    public void output()
    {
        Console.WriteLine (
"success");
    }
}
struct constructD
{
    
public constructD(int a)//这里只可以重载结构体的带参的构造函数
    {
        Console.WriteLine (a);
    }
    
public void output()
    {
        Console.WriteLine (
"success");
    }
}
class test
{
    
static void Main()
    {
        constructC cc
=new constructC ();//调用结构体默认的构造函数
        cc.output ();
        
        constructD cd
=new constructD ();//同类不一样,这种实例化的方式也是对的。
        cd.output ();
        
        constructD cd2
=new constructD (5);//调用结构体带参的构造函数
    }
}

通过上面的比较,相信你已经能掌握结构体与类中的构造函数的异同了。
posted @ 2009-08-26 13:09  爱生活,爱GIS  阅读(790)  评论(0编辑  收藏  举报