Inside C#(一些內部實現的東西)

來源:互聯網
上載者:User
ILDASM是個好的工具,平時也很喜歡用,它能協助我更好的瞭解NET。以下我的總結,請執教。

You write:

public enum Compression {

   Zip, SuperZip, None

 }

The C# compiler generates:

public struct Compression : Enum {

   public int value__;

   public const Compression Zip = 0;

   public const Compression SuperZip = 1;

   public const Compression None = 2;

}
What can we learn:

1)Enums 是struct ,內部成員即是struct 也是Enum 。
2)Enum 繼承System.Enum 的,structs可以繼承ValueType,也可以是Enum 。
3)Enum 內部成員預設是Int的。
4)變數含有”__“的不能使用。
5)所有的值都是const 的,因此在沒有重新編譯的時候是不能改變的,而且也是型別安全的。
 

You write:

public class Resource

{

   ~Resource() {

      ...

   }

}

The C# compiler generates:

public class Resource

{

   protected override void Finalize() {

      try {

         ...

      }

      finally {

         base.Finalize();

      }

   }

}

What can we learn:
1)解析函數是重寫基類的finalize 的。且是不確定的。
2)method (represented by the “…”)是放在Try裡,無論有沒有異常都會調用基類的finalize 。

You write:

using (Resource res = new Resource()) {

   res.DoWork();

}

The C# compiler generates:

Resource res = new Resource(...);

try {

   res.DoWork();

}

finally {

   if (res != null)
      ((IDisposable)res).Dispose();

}

What can we learn:

使用using 會被編譯成try,且會始終執行Dispose方法(基於CLR的異常)。

You write:

object x = ... ;

lock (x) {

   // critical section

}

The C# compiler generates:

System.Threading.Monitor.Enter(x);
try {
   // critical section
}
finally {
   System.Threading.Monitor.Exit(x);
}

What can we learn:
1)       Lock just uses Monitor.Enter and Exit… reading those docs give you a good idea of what is really happening here.
2)       We see our friend try..finally again. This time ensuring that the monitor is exited even if an exception is thrown in the critical section

You write:
ArrayList list = new ArrayList();
foreach(int x in list) { // do nothing }

The C# compiler generates:
ArrayList list1;
int num1;
IEnumerator enumerator1;
IDisposable disposable1;
list1 = new ArrayList();
enumerator1 = list1.GetEnumerator();
try { 
        while (enumerator1.MoveNext()) { 
            num1 = ((int) enumerator1.Current);
         } 
        return;
 }
finally { 
            disposable1 = (enumerator1 as IDisposable); 
            if (disposable1 != null) { 
                    disposable1.Dispose(); 
                }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.