黑马程序员技术交流社区

标题: 一个构造函数能否调用另一个构造函数,如果能请写出简... [打印本页]

作者: 嘴角上揚ぃ读不    时间: 2014-5-1 20:33
标题: 一个构造函数能否调用另一个构造函数,如果能请写出简...
本帖最后由 嘴角上揚ぃ读不 于 2014-5-6 20:25 编辑

一个构造函数能否调用另一个构造函数吗?如果能请写出简单的代码。
作者: 朝花夕拾_黑马    时间: 2014-5-1 21:03
  1. <font size="4">using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace ConsoleApplication1
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             B b = new B();
  12.             Console.ReadKey();
  13.         }
  14.     }
  15.     public class A
  16.     {
  17.       public A()
  18.     {
  19.       Console.WriteLine("A");
  20.     }
  21.     }

  22.     public class B
  23.     {
  24.         public B()
  25.         {
  26.    A a = new A();//这样new个A类型对象,自动调用A类的构造函数
  27.         }   
  28.     }
  29. }
  30. </font>
复制代码



作者: 亚伦    时间: 2014-5-1 21:58
  1. class Employee
  2.     {
  3.         public int ID { get; set; }
  4.         public string Name { get; set; }
  5.         public Employee()
  6.         {
  7.             Console.WriteLine("In MyClass()");
  8.         }
  9.         public Employee(int id) : this() // 在这里,调用了MyClass()
  10.         {
  11.             ID = id;
  12.             Console.WriteLine("In MyClass(int id)");
  13.         }
  14.         public Employee(int id, string name) : this(id) // 在这里,调用了MyClass(int id)
  15.         {
  16.             Name = name;
  17.             Console.WriteLine("In MyClass(int id, string name)");
  18.         }
  19.     }
  20.     class Program
  21.     {
  22.         static void Main(string[] args)
  23.         {
  24.             Employee mc = new Employee(1);
  25.         }
  26.     }
复制代码
请亲自把该代码编译一次,建议设置断点观察程序运行的流程,有问题请跟我讨论。





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2