Learning CLR via C#(3)

來源:互聯網
上載者:User
  1. CLR要求將介面方法標記為virtual,如果原始碼中沒有顯示地將方法標記為virtual,編譯器會將它們標記為virtual和sealed,這會阻止衍生類別重寫介面方法。
  2. 一個類型載入到CLR中時,會為該類型建立並初始化一個方法表。在這個方法表中,類型引入的每個新方法都有一條對應的記錄項;另外,還為該類型繼承的所有虛方法添加了記錄項。
  3. 可以用顯示介面方法實現(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);    }}
  1. CLR將所有多維陣列都視為非0基數組。訪問一維0基數組的元素比訪問非0基一維數組或多維陣列稍快一些。
  2. 記憶體回收:
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層面是沒有區別的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.