C# 构造方法(函数)
构造方法的作用
构造方法用来创建对象,并且在构造方法中对对象进行初始化。
构造方法的特殊性
- 没有返回值,不需要写类型,连void都不要写。
- 构造方法的方法名,与类名要相同。
构造方法结构
public 类名(参数类型 参数1,参数类型 参数2,......){
把参数赋值给属性。
}
构造方法使用
- 创建对象时,会先执行构造方法。
- 构造方法是可以重载的。(学习方法重载:https://blog.csdn.net/shenqiankk/article/details/97412815 )
构造方法一定要用public修饰符。
因为Person p = new Person();
创建p的时候,new需要做3件事才能完成实例化:- 在内存开辟一块空间。
- 在开辟的空间中存放p对象。
- 调用对象的【构造方法】进行初始化。
所以构造方法必须可被外界调用。
class Person
{
//构造方法
public Person(string name, int age, string sex, int chinese, int math, int english)
{
this.Name = name;
this.Age = age;
this.Sex = sex;
this.Chinese = chinese;
this.Math = math;
this.English = english;
}
//构造方法重载
public Person(string name, int age, string sex)
{
this.Name = name;
this.Age = age;
this.Sex = sex;
}
//构造方法重载
public Person()
{
}
//字段
private string _name;
private int _age;
private string _sex;
private int _chinese;
private int _math;
private int _english;
//属性
public string Name
{
set { _name = value; }
get { return _name; }
}
public int Age
{
set { _age = value; }
get { return _age; }
}
public string Sex
{
set { _sex = value; }
get { return _sex; }
}
public int Chinese
{
set { _chinese = value; }
get { return _chinese; }
}
public int Math
{
set { _math = value; }
get { return _math; }
}
public int English
{
set { _english = value; }
get { return _english; }
}
//自我介绍方法
public void Introduce()
{
Console.WriteLine("大家好,我叫{0},我是{1}生,我今年{2}岁,我语文{3}分,数学{4},英语{5}"
, this.Name, this.Sex, this.Age, this.Chinese, this.Math, this.English);
}
}
class Program
{
static void Main(string[] args)
{
//创建小明对象
Person p1 = new Person("小明",15,"男",60,80,50);
//调用自我介绍方法
p1.Introduce();
//创建小红对象
Person p2 = new Person();
//赋值
p2.Name = "小红";
p2.Age = 14;
p2.Sex = "男";
p2.Chinese = 80;
p2.Math = 60;
p2.English = 90;
//调用自我介绍方法
p2.Introduce();
}
}
还没有评论,来说两句吧...