构造函数实例
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
//2014.3.13
namespace 构造函数 {
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
Person p2 = new Person("tom");
Person p3 = new Person("jerr",18);
Console.WriteLine("年龄是{0},名字叫{1}",p1.Age,p1.Name);
Console.WriteLine("年龄是{0},名字叫{1}", p2.Age, p2.Name);
Console.WriteLine("年龄是{0},名字叫{1}", p3.Age, p3.Name);
Console.ReadKey();
}
}
/// <summary>
/// 函数名和类名一样,没有返回值,连void都不用。
/// 构造函数用来创建对象,并且可以在构造函数中对对象进行初始化
/// 构造函数可以重载
/// </summary>
class Person
{
public string Name { get;set; }
public int Age { get; set; }
public Person()
{
Name = "未命名";
Age = 0;
}
public Person(string name)
{
this.Name = name;
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
}