023 什么是类 · 语雀 https://www.yuque.com/yuejiangliu/dotnet/timothy-csharp-023
C#5

数据类型:
类-引用类型-每1个类都是1个自定义引用类型
1.声明变量
2.创建实例-类的实例化-类是实例的模板
反射-不用new操作符创建实例
//反射
Type t = typeof(Student);
默认构造器
//object o1 = Activator.CreateInstance(t);
//实例构造器
object o2 = Activator.CreateInstance(t, 3, "Tom");
//Console.WriteLine(o2.GetType());//HelloClass.Student
//Console.WriteLine(o2.GetType().Name);//Student
//创建出来的t是object类型,需要强转
//1
Student stu3 = (Student)o2;
//2
Student stu4 = o2 as Student;
stu3.Report();
stu4.Report();
dynamic编程
//dynamic编程
Type t2 = typeof(Student);
dynamic stu5 = Activator.CreateInstance(t2, 4, "Jack");
Console.WriteLine(stu5.Name);
构造器和析构器
构造器-和类名相同,无返回值
默认构造器
实例构造器-一旦有了实例构造器,编译器就不会再生成默认构造器
static构造器-只能用来初始化static成员
C#6新语法-字符串解析-cw($"{ID},{Name}");
java/C#-托管类编程语言-Gc垃圾收集器
c/cpp-内存泄漏
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)
????????{
????????????默认构造器
????????????{}-初始化器
????????????//var stu1 = new Student() { ID = 1, Name = "Timothy" };
????????????实例构造器
????????????//var stu2 = new Student(2, "Tim");
????????????//反射
????????????Type t = typeof(Student);
????????????默认构造器
????????????//object o1 = Activator.CreateInstance(t);
????????????//实例构造器
????????????object o2 = Activator.CreateInstance(t, 3, "Tom");
????????????//Console.WriteLine(o2.GetType());//HelloClass.Student
????????????//Console.WriteLine(o2.GetType().Name);//Student
????????????//创建出来的t是object类型,需要强转
????????????//1
????????????Student stu3 = (Student)o2;
????????????//2
????????????Student stu4 = o2 as Student;
????????????stu3.Report();
????????????stu4.Report();
????????????//dynamic编程
????????????Type t2 = typeof(Student);
????????????dynamic stu5 = Activator.CreateInstance(t2, 4, "Jack");
????????????Console.WriteLine(stu5.Name);
????????}
????}
????class Student
????{
????????public int ID { get; set; }
????????public string Name { get; set; }
????????//static成员
????????public static int Amount { get; set; }
????????public void Report()
????????{
????????????Console.WriteLine("{0},{1}", ID, Name);
????????}
????????//实例构造器
????????public Student(int id, string name)
????????{
????????????this.ID = id;
????????????this.Name = name;
????????????Amount++;
????????}
????????//static构造器
????????static Student()
????????{
????????????Amount = 0;
????????}
????????//析构器
????????~Student()
????????{
????????????Amount--;
????????????Console.WriteLine("bye");
????????}
????}
}

|