C#语言中类的构造函数详解

来源:互联网 发布:cdr软件图标 编辑:程序博客网 时间:2024/05/24 04:30
原文地址:C#语言中类的构造函数详解作者:摆渡者

    大家都知道,在C#类中有一个最为特殊的方法——构造函数,它没有返回值且方法名称与类名相同。任何时候只要创建类,就会调用类的构造函数。同样,构造函数支持方法重载——这样就为类的使用者提供了多条实例化类的对象的途径。上述的这些观点相信大家都能理解,但构造函数的其他的一些特点你有所了解吗?本文将深入讲解构造函数。

默认构造函数

    在默认情况下(也就是在类的定义中并没有明确写出构造函数的实现)C#将创建一个构造函数,该构造函数自动实例化对象,将对象的成员变量设置为其成员变量类型的默认值,C#中各类数据类型的默认值见下表:

数据类型

默认值

boolfalsebyte0char‘’decimal0.0Mdouble0.0Menum枚举值组合的第一个值float0.0Fint0long0Lsbyte0short0struct将所有的值类型字段设置为默认值,将所有的引用类型字段设置为null时产生的值uint0ulong0ushort0

    如果我们在类的定义中明确的写出了带参数的构造函数,如下面的代码:

   1: public class Student
   2: {
   3:     private string name;    
   4:     public string Name
   5:     {
   6:         get { return this.name; }
   7:         set { this.name = value; }
   8:     }
   9:  
  10:     private int age;    
  11:     public int Age
  12:     {
  13:         get { return this.age; }
  14:         set { this.age = value; }
  15:     }
  16:  
  17:     public Student(string name, int age)
  18:     {
  19:         this.name = name;
  20:         this.age  = age;
  21:     }
  22: }

    在使用上面定义的Student类时,如下的代码编译将失败,编译器提示“‘Student’方法没有采用‘0’个参数的重载”:

   1: class Program
   2: {
   3:     static void Main()
   4:     {
   5:         Student stu = new Student();
   6:     }
   7: }

     为了能够使上面这段使用Student类的代码编译通过,我们需要在上面的Student类定义代码中添加一句“废话”:

   1: public Student() {}

    这是关于默认构造函数我们需要注意的地方。

构造函数在类内部的调用

    构造函数在实例化类的对象是通过new关键字来调用,这个大家都知道。但在类的内部,我们怎么直接调用其构造函数呢?我们只能通过this关键字来调用,并且我们只能在构造函数的方法声明中调用类的另外一个构造函数,样例代码如下:

   1: public class Student
   2: {
   3:     private string name;
   4:     public string Name
   5:     {
   6:         get { return this.name; }
   7:         set { this.name = value; }
   8:     }
   9:  
  10:     private int age;
  11:     public int Age
  12:     {
  13:         get { return this.age; }
  14:         set { this.age = value; }
  15:     }
  16:  
  17:     private string grade;
  18:     public string Grade
  19:     {
  20:         get { return this.grade; }
  21:         set { this.grade = value; }
  22:     }
  23:  
  24:     public Student() 
  25:     {
  26:         Console.WriteLine("一个学生对象被实例化");
  27:     }
  28:  
  29:     public Student(string name, int age)
  30:         : this()
  31:     {
  32:         this
原创粉丝点击