16.4 Retrieving modules from an assembly


An assembly can consist of one or more modules. [1] To obtain an array of modules in an assembly, you use System.Reflection.Assembly 's GetModules method.

[1] A module is a file containing IL codes but without a manifest. Each assembly must have one and only one manifest file regardless of the number of modules it contains.

Let's create an assembly (called Assm ) containing two modules ( Mod1 and Mod2 ) first. The following three code fragments do just that.

 1: // Mod1.cs 2: public class Mod1{} 
 1: // Mod2.cs 2: public class Mod2{} 
 1: // Assm.cs  2: using System;  3: using System.Reflection;  4:  5: public class Assm{  6:   public static void Main(){  7:  Assembly a  =  Assembly.LoadFrom("Assm.exe");  8:  Module[] modules  =  a.GetModules();  9:     foreach(Module m in modules) 10:       Console.WriteLine(m); 11:   } 12: } 

If you are using csc.exe , compile the two module files Mod1.cs and Mod2.cs into module files first (module files end with a .netmodule extension). Use the /target:module option of csc.exe :

 c:\expt>csc /target:module Mod1.cs c:\expt>csc /target:module Mod2.cs 

Mod1.netmodule and Mod2.netmodule will be created.

(You can also use the option shortcut /t:module instead of /target:module .)

Then compile Assm.cs by adding into it the two module files you have just created. Use the /addmodule option to do this. If there is more than one module to be added into the final assembly file, separate them using commas without any spaces:

 c:\expt>csc /addmodule:Mod1.netmodule,Mod2.netmodule Assm.cs 

The assembly file Assm.exe will be created. When executed, Assm.exe will produce the following output.

 c:\expt>assm Assm.exe Mod1.netmodule Mod2.netmodule 

The Assm assembly contains three modules in all “ the Assm class itself, Mod1 , and Mod2 . Their names are displayed by reflection.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net