作用:简化代码
示例:输出学生信息:张三20岁,是男孩;小美23岁,是女孩。
class Student
{ //定义学生的属性:名字,年龄,性别
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
//构造函数 函数名与类名相同 可以有参数 也可以无参数 示例是有参数的
public Student(string name, int age, string sex)
{//this.Name表示定义的属性 name表示传入的参数
this.Name = name;
this.Age = age;
this.Sex = sex;
}
public void show()
{
Console.WriteLine("名字:{0},年龄:{1},性别:{2}", this.Name, this.Age, this.Sex);
}
}
class Program
{
static void Main(string[] args)
{ //方便之处在于实例化时直接传参数就能打印出结果了,不然的话需要
一行代码输入姓名;
一行代码输入年龄;
一行代码输入性别;
再打印
Student pr1 = new Student("张三",20,"男");
Student pr2 = new Student("小美", 23, "女");
pr1.show();
pr2.show();
}
}