Assembly(c#中簡單說明)

來源:互聯網
上載者:User
Assembly(c#中簡單說明)2008-07-11 00:27

什麼是Assembly(程式集)?
Assembly是一個包含來程式的名稱,版本號碼,自我描述,檔案關聯關係和檔案位置等資訊的一個集合。在.net架構中通過Assembly類來支援,該類位於System.Reflection下,物理位置位於:mscorlib.dll。

Assembly能幹什嗎?
我們可以通過Assembly的資訊來擷取程式的類,執行個體等編程需要用到的資訊。

一個簡單的示範執行個體:
1.建立一個Console工程名為:NamespaceRef
2.寫入如下代碼:

1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Reflection;
5
6namespace NamespaceRef
7{
8    class Program
9    {
10        static void Main(string[] args)
11        {
12             Country cy;
13             String assemblyName = @"NamespaceRef";
14            string strongClassName = @"NamespaceRef.China";
15            // 注意:這裡類名必須為強類名
16            // assemblyName可以通過工程的AssemblyInfo.cs中找到
17             cy = (Country)Assembly.Load(assemblyName).CreateInstance(strongClassName);
18             Console.WriteLine(cy.name);
19             Console.ReadKey();
20         }
21     }
22
23    class Country
24    {
25        public string name;
26     }
27
28    class Chinese : Country
29    {
30        public Chinese()
31        {
32             name = "你好";
33         }
34     }
35
36    class America : Country
37    {
38        public America()
39        {
40             name = "Hello";
41         }
42     }
43}

由於Assembly的存在給我們在實現設計模式上有了一個更好的選擇。
我們在開發的時候有時候會遇到這樣的一個問題,根據對應的名稱來建立指定的對象。如:給出chinese就要建立一個chinese對象,以前我們只能這樣來寫代碼:1if (strongClassName == "China")
2     cy = new China();
3else if (strongClassName == "America")
4     cy = new America();

那麼如果我們有很長的一系列對象要建立,這樣的代碼維護起來是很困難的,而且也不容易閱讀。現在我們可以通過在外部檔案定義類的程式集名稱和類的強式名稱來獲得這樣一個執行個體,即易於理解,又增強了擴充性還不用修改代碼。
cy = (Country)Assembly.Load(assemblyName).CreateInstance(strongClassName);

結論
Assembly類有很多的方法和屬性,它和Type一樣有很多功能用於名稱與方法和屬性之間的轉化。深入理解這兩個類,你就可以清晰通用語言層是如何工作。

聯繫我們

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