- CLR要求將介面方法標記為virtual,如果原始碼中沒有顯示地將方法標記為virtual,編譯器會將它們標記為virtual和sealed,這會阻止衍生類別重寫介面方法。
- 一個類型載入到CLR中時,會為該類型建立並初始化一個方法表。在這個方法表中,類型引入的每個新方法都有一條對應的記錄項;另外,還為該類型繼承的所有虛方法添加了記錄項。
- 可以用顯示介面方法實現(EIMI)來增強編譯時間的型別安全:
internal struct SomeValueType : IComparable{ private int _value; public SomeValueType(int value) { _value = value; } public int CompareTo(SomeValueType other) { return _value - other._value; } int IComparable.CompareTo(object other) { return CompareTo((SomeValueType)other); }}
CLR將所有多維陣列都視為非0基數組。訪問一維0基數組的元素比訪問非0基一維數組或多維陣列稍快一些。
記憶體回收:
public void Test(){ Timer t = new Timer(TimerCallBack, null, 0, 2000); Console.ReadLine();}private void TimerCallBack(object state){ Console.WriteLine("In TimerCallBack: " + DateTime.Now.ToString()); GC.Collect();}
Timer只會執行一次。
public void Test(){ using (Timer t = new Timer(TimerCallBack, null, 0, 2000)) { Console.ReadLine(); }}
可以正確多次執行。
- 如果一個類型定義了Finalize方法,那麼在該類型的執行個體構造器被調用之前,會將指向該對象的一個指標放到一個終結列表中。當記憶體回收開始時,記憶體回收行程會掃描終結列表尋找垃圾對象的指標,如果找到,該指標會從終結列表中移除,並追加到freachable列表中。一個特殊的高優先順序CLR線程專門負責調用Finalize方法。加到freachable中的指標指向的對象不會被回收記憶體直到Finalize方法被調用。
- GC中新建立的對象屬於第0代,在對第0代回收中存活下來的對象提升為第1代,對第1代回收中存活下來的對象提升為第2代。代越高分配的記憶體預算就越大,回收頻率越低。
- 跨AppDomain通訊的方式:1.按引用封送(繼承MarshalByRefObject)。2.按值封送(可序列化)。
- 對於帶有ref,out等參數的反射調用:
internal sealed class SomeType{ public void RefMethod(ref int a) { a += 3; }}
可以使用
typeof(int).MakeByRefType()
或
Type.GetType("System.Int32&")
來獲得參數Type資訊。
public void Test(){ object[] args = new object[] { 12 }; Type t = typeof(SomeType); MethodInfo method = t.GetMethod("RefMethod", new[] { typeof(int).MakeByRefType() }); method.Invoke(new SomeType(), args); Console.WriteLine(args[0]); method = t.GetMethod("RefMethod", new[] { Type.GetType("System.Int32&") }); method.Invoke(new SomeType(), args); Console.WriteLine(args[0]);}
out和ref的調用方式完全一樣,因為兩者在IL層面是沒有區別的。