学习C#的第七天
-
构造函数 和 析构函数 补
- 构造函数 - 构造函数没有返回值,不能写void,必须public - 构造函数必须跟类名一样 - 构造函数是可以重载的
namespace test4
{
public enum Gender
{
男,
女
}
class Clerk
{
private string _name;
public string Name { get => _name; set => _name = value; }
private Gender _gender;
public Gender Gender { get => _gender; set => _gender = value; }
private int _age;
public int Age { get => _age; set => _age = value; }
private string _dep;
public string Dep { get => _dep; set => _dep = value; }
public void Write()
{
Console.WriteLine("{0},{1},{2},在{3}任职", this.Name, this.Gender, this.Age, this.Dep);
}
public void Write2()
{
Console.WriteLine("{0},{1},{2}", this.Name, this.Gender, this.Age);
}
public Clerk(string name, Gender gender, int age, string dep)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
this.Dep = dep;
}
//Clerk方法重载
public Clerk(string name, Gender gender, int age)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
}
}
}
- 析构函数
- 析构函数是一种销毁类的实例的方法成员
- 不能有参数,不能修饰符,不能被调用
- 有前缀 ~
- 只有在类执行完成后,析构函数才会执行
-
类的继承
- 单根性 - 传递性 - 派生类定义与基类同名的成员,会覆盖基类成员 使用new关键字覆盖 - 派生类不能继承基类的构造函数成员
namespace test4
{
class Clerk
{
private string _name;
public string Name { get => _name; set => _name = value; }
private string _dep;
public string Dep { get => _dep; set => _dep = value; }
public void Write()
{
Console.WriteLine("大家好,我是{0}的{1}", this.Dep, this.Name);
}
public Clerk(string dep, string name)
{
this.Dep = _dep;
this.Name = _name;
}
}
}
------------------------------------------------------------------------------------------------------------------------
namespace test4
{
class Sales : Clerk
{
private int _salesTarget;
public int SalesTarget { get => _salesTarget; set => _salesTarget = value; }
public void Write2()
{
Console.WriteLine("大家好,我是{0}的{1},我的销售目标是{2}", this.Dep, this.Name, this.SalesTarget);
}
//通过base() 来实现来调用基类的构造函数
public Sales(string name, string dep, int SalesTarget) : base(name, dep)
{
this.SalesTarget = _salesTarget;
}
}
}
- 如果希望一个类不作为基类,使用关键字sealed
- 抽象类只能作为基类
- 子类的访问权限不能超过父类的访问权限
-
类的封装
- 修饰符 - public - private - protected 只能在定义的当前类 或者 子类中使用 - interal 只能在当前项目中访问 - protected interal 允许一个类将其成员变量 和 成员函数对同一应用程序内子类以外的其他的类和对象进行隐藏 - 能够修饰类访问的修饰符只有 public private
-
类的多态