黑马程序员技术交流社区
标题:
一个构造函数能否调用另一个构造函数,如果能请写出简...
[打印本页]
作者:
嘴角上揚ぃ读不
时间:
2014-5-1 20:33
标题:
一个构造函数能否调用另一个构造函数,如果能请写出简...
本帖最后由 嘴角上揚ぃ读不 于 2014-5-6 20:25 编辑
一个构造函数能否调用另一个构造函数吗?如果能请写出简单的代码。
作者:
朝花夕拾_黑马
时间:
2014-5-1 21:03
<font size="4">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
B b = new B();
Console.ReadKey();
}
}
public class A
{
public A()
{
Console.WriteLine("A");
}
}
public class B
{
public B()
{
A a = new A();//这样new个A类型对象,自动调用A类的构造函数
}
}
}
</font>
复制代码
作者:
亚伦
时间:
2014-5-1 21:58
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public Employee()
{
Console.WriteLine("In MyClass()");
}
public Employee(int id) : this() // 在这里,调用了MyClass()
{
ID = id;
Console.WriteLine("In MyClass(int id)");
}
public Employee(int id, string name) : this(id) // 在这里,调用了MyClass(int id)
{
Name = name;
Console.WriteLine("In MyClass(int id, string name)");
}
}
class Program
{
static void Main(string[] args)
{
Employee mc = new Employee(1);
}
}
复制代码
请亲自把该代码编译一次,建议设置断点观察程序运行的流程,有问题请跟我讨论。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2