類與聲明
什么是類?
前情總結
前面22講的課基本上就做了兩件事
- 學習C#的基本元素
- 學習類的成員
析構函數:
當對象不再被引用的時候,就會被垃圾回收器gc,回收。而收回的過程當中,如果需要做什么事情,就放在析構函數中來做。
gc是托管類語言的特色,比如C#、Java。
有的時候,gc沒有釋放一些底層的資源,就需要在析構函數中,去手動的釋放資源
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace HelloClass {internal class Program {static void Main(string[] args) {//通過反射找回類型Type t = typeof(Student);object obj = Activator.CreateInstance(t, 1, "Timothy");//可以不通過new操作符去創建對象Student stu = obj as Student;Console.WriteLine(stu.Name);//dynamic也可以創建對象dynamic stu2 = Activator.CreateInstance(t, 2, "Max");//動態的去找Console.WriteLine(stu2.Name);}}class Student {public static int Amount { get; set; }static Student() {Amount = 100;}public Student(int id, string name){ID = id;Name = name;Amount++;}//析構函數~Student() {Amount--;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}");}}
}
類的聲明
C++中類的聲明與定義是可以分開的。
而C#和Java中聲明和定義是分不開的,所以聲明即定義
類聲明的位置:名稱空間中、類體中、全局名稱空間內其他名稱空間外
類的訪問級別的修飾符:public
和internal
public
即其他項目(Assembly)中的類也可以訪問
internal
實際上就是默認的情況,在本項目(Assembly)中來自由訪問這個被修飾的類
class Student{}
internal class Student{}
//兩者是等同的
常見的裝配集(Assembly)就兩種,.exe
可執行文件和類庫
的類
class Student{}
internal class Student{}
//兩者是等同的
常見的裝配集(Assembly)就兩種,.exe
可執行文件和類庫