C#中构造方法重载的相互调用
在C#中,构造函数可以使用 this 关键字调用同一对象中的另一构造函数。和 base 一样,this 可带参数使用也可不带参数使用,构造函数中的任何参数都可用作 this 的参数,或者用作表达式的一部分。
namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
Employee emp2 = new Employee("Tom");
Employee emp3 = new Employee("Lee", 30);
Console.WriteLine("使用默认构造方法:Name={0}, Age={1}", emp1.Name, emp1.Age);
Console.WriteLine("使用带名字参数的构造方法:Name={0}, Age={1}", emp2.Name, emp2.Age);
Console.WriteLine("使用带全参数的构造方法:Name={0}, Age={1}", emp3.Name, emp3.Age);
Console.ReadLine();
}
}
public class Employee {
string _name;
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// 默认构造方法
/// </summary>
public Employee()
:this("NoName", 0)
{
//_name = "NoName";
}
/// <summary>
/// 带名字参数的构造方法
/// </summary>
/// <param name="name"></param>
public Employee(string name)
: this(name, 0)
{
//_name = name;
}
/// <summary>
/// 带全参数的构造方法
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public Employee(string name, int age) {
_name = name;
_age = age;
}
}
}
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
Employee emp2 = new Employee("Tom");
Employee emp3 = new Employee("Lee", 30);
Console.WriteLine("使用默认构造方法:Name={0}, Age={1}", emp1.Name, emp1.Age);
Console.WriteLine("使用带名字参数的构造方法:Name={0}, Age={1}", emp2.Name, emp2.Age);
Console.WriteLine("使用带全参数的构造方法:Name={0}, Age={1}", emp3.Name, emp3.Age);
Console.ReadLine();
}
}
public class Employee {
string _name;
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// 默认构造方法
/// </summary>
public Employee()
:this("NoName", 0)
{
//_name = "NoName";
}
/// <summary>
/// 带名字参数的构造方法
/// </summary>
/// <param name="name"></param>
public Employee(string name)
: this(name, 0)
{
//_name = name;
}
/// <summary>
/// 带全参数的构造方法
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public Employee(string name, int age) {
_name = name;
_age = age;
}
}
}