一、什么是类?
1.类是一种数据结构(抽象的结果,抽象的载体)
类是一种数据结构,它可以包含数据成员(常量和字段)、函数成员(方法、事件、索引器、运算符、实例构造函数、静态构造函数和析构函数)以及嵌套类型。类类型支持继承,继承是一种机制,它使派生类可以对基类进行拓展和专用化
----《C#语言规范》
2.是一种数据类型
类是一种引用类型,具体到每一个类上,都是一个自定义的类型
3.代表着现实世界中的“种类”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloClass
{
class Program
{
static void Main(string[] args)
{
// Student stu; //声明一个变量
// Student stu = new Student() { ID =1,Name="Timothy"};//创建一个实例
//若你不使用初始化器,得出的值会是0,这就默认构造器在起作用
//Type t = typeof(Student);//反射基础
//object o = Activator.CreateInstance(t, 2, "Parker");//会有类型丢失,无法使用Student的方法、属性,但可以找回
//Student stu1 = o as Student;//找回类
//Console.WriteLine(stu1.ID);//可以正常使用方法属性
//Type t = typeof(Student);
//dynamic stu2 = Activator.CreateInstance(t, 3, "pop");//dynamic编程
//Console.WriteLine(stu2.Name);//不会有智能提示,但是找到Name
Student s1 = new Student(1,"Timothy");
Student s2 = new Student(2, "parker");
Console.WriteLine(Student.Amount);
}
}
class Student
{
public static int Amount { get; set; }//静态属性
static Student()//静态构造器,用来初始化静态成员
{
Amount = 100;//student类一加载到内存之中就有100个
}
~Student()
{
Amount--;
Console.WriteLine(Amount) ;//用完就-1
}
public Student(int id,string name)//ctor+tabx2,自己的构造器;名字要跟类名一样,长得很像方法但是没有返回值
{
this.ID = id;//ID就用传进来的值
this.Name = name;
Amount++;//有实例被创建就+1
}
///类就像一个模板,有一个默认构造器,当我们想对一个实例进行个性化的时候,就自己造一个构造器进行修改
//~Student()//处理垃圾内存的地方,程序使用完毕后就会调用析构器
//{
// Console.WriteLine("Bye bye!Release the system resources..");
//}
public int ID { get; set; }
public string Name { get; set; }
public void Report()
{
Console.WriteLine($"I'm #{ID} student,my name is {Name}");
}
}
}