面向对象的三个主要特征:封装、继承、多态。
类的成员:字段、属性、方法、事件。
1、类是一种抽象的数据结构,类本身是抽象的结果,类也是抽象结果和抽象行为的载体。
2、类是一种数据类型:引用类型。Student类是一个类型。具体到每一个类上,每一个类都是一种自定义数据类型。那么这个类可以用来声明变量、创建实例(可以被视为实例的模板)。
3、类代表着现实世界中的“种类”。
如果在类中没有写我们自己的构造器(构造函数),那么实例化对象时的括号()就会去调用类的默认构造器,将属性赋值为相应的零值。VS写法ctor。可以加入初始化参数,类似__init__函数。
有些类,在别的地方都没有调用时,系统会将其自动回收。如果没有自动回收,需要我们自己写析构函数来释放内存。写法为ctor然后将public换成~。
如何不用new操作符,创造给定类型的实例。
class Program
{
static void Main(string[] args)
{
Student student1 = new Student(1, "laotie");
student1.Report();
// 不用new操作符实例化一个对象。
//方法一
Type t = typeof(Student);
object o = Activator.CreateInstance(t, 2, "zijianwang");
// 以上两行是反射的基础。
//Student stu = (Student)o;
Student stu = o as Student;
stu.Report();
//方法二:dynamic方式;
dynamic stu2 = Activator.CreateInstance(t, 3, "tom");
stu2.Report();
Console.ReadLine();
}
}
class Student
{
public int ID { get; set; }
public string Name { get; set; }
// 构造函数
public Student(int id, string name)
{
this.ID = id;
this.Name = name;
}
public void Report()
{
Console.WriteLine($"I'm #{ID} student, my name is {Name}.");
}
//析构函数
~Student()
{
}
}
当类表示对现实事件中类群的抽象时,其静态成员用来表述类群的特征;比如学生的总数,静态构造器。静态构造器只能用来构造初始化静态成员。
class Program
{
static void Main(string[] args)
{
Student student1 = new Student(1, "laotie");
Student stu1 = new Student(2, "tom");
Console.WriteLine(Student.Amount);// Student代表族群。
student1.Report();
}
}
class Student
{
public static int Amount { get; set; }
//静态构造器。
static Student()
{
Amount = 100;
}
public int ID { get; set; }
public string Name { get; set; }
// 构造函数,创建学生实例时,加一
public Student(int id, string name)
{
this.ID = id;
this.Name = name;
Student.Amount++;
}
public void Report()
{
Console.WriteLine($"I'm #{ID} student, my name is {Name}.");
}
//析构函数,释放资源时,减一;
~Student()
{
Amount--;
}
}