大纲
- 前22讲的简要总结:封装,现实世界的东西抽象出来封装在类里面
- 什么是“类”:是一种数据结构,是一种数据类型,代表现实世界中的“种类”
《C#语言规范》类是一种数据结构,它可以包含数据成员(常量和字段)、函数成员(方法、属性、事件、索引器、运算符、实例构造函数、静态构造函数和析构函数)以及嵌套类型。类类型支持继承,继承是一种机制,它使派生类可以对基类进行扩展和专用化。
- 构造器与析构器(实例与静态)
- 后面:继承和多态
类的概念
- 类是一种抽象数据结构(data structure),枢纽和支点
- 类是一种数据类型,类是一种引用类型,每一个类都是一个自定义类型。
- 代表现实世界中的“种类” ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ClassDefinition { public delegate void Report(); class Program { static void Main(string[] args) { Student student = new Student(1, “Timothy”); Report report = new Report(student.Report); report.Invoke(); } }
class Student{//实例构造器public Student(int id,string name){this.ID = id;this.Name = name;}public int ID { get; set; }public string Name { get; set; }public void Report(){Console.WriteLine($"I'm #{this.ID} student ,my name is {this.Name}");//C#6$新语法解析}}
}
<a name="nXg7N"></a># 实例构造器、析构器析构器用于手动释放资源。<br />格式:~类名(){}<br />当程序执行到new完student实例后则消失了,对象就没有引用了,这时候执行析构器,释放资源。```csharpusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 析构器{class Program{static void Main(string[] args){Student student = new Student(1, "Albert");}}class Student{public string m_Name { get; set; }public int m_Number { get; set; }public Student(int number,string name){this.m_Name = name;this.m_Number = number;}//析构器~Student(){Console.WriteLine("Byebye!Release the system resource...");}}}
反射基础
类是一种类型。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 析构器{class Program{static void Main(string[] args){Student student = new Student(1, "Albert");//反射 展现类是一种类型(模板),引用类型,自定义类型Type t = typeof(Student);//Activator:包含特定的方法,用以在本地或从远程创建对象类型,//或获取对现有远程对象的引用。 此类不能被继承。object o = Activator.CreateInstance(t,1,"Jack");Student student1 = o as Student;Console.WriteLine(student1.m_Name);}}class Student{public string m_Name { get; set; }public int m_Number { get; set; }public Student(int number,string name){this.m_Name = name;this.m_Number = number;}//析构器~Student(){Console.WriteLine("Byebye!Release the system resource...");}}}
Dynamic编程
Dynamic编程
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 析构器{class Program{static void Main(string[] args){Student student = new Student(1, "Albert");//反射 展现类是一种类型(模板),引用类型,自定义类型Type t = typeof(Student);//Activator:包含特定的方法,用以在本地或从远程创建对象类型,//或获取对现有远程对象的引用。 此类不能被继承。dynamic o = Activator.CreateInstance(t,1,"Jack");Console.WriteLine(o.m_Name);}}class Student{public string m_Name { get; set; }public int m_Number { get; set; }public Student(int number,string name){this.m_Name = name;this.m_Number = number;}//析构器~Student(){Console.WriteLine("Byebye!Release the system resource...");}}}
静态构造器
static Student(){}
