Csharp/CSharp Tutorial/Assembly/Assembly Load

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Assemblies

To quote Microsoft, "Assemblies are the building blocks of the .NET Framework."

An assembly is composed of four sections.

  1. The first is the assembly manifest.
  2. The manifest contains information about the assembly itself.
  3. The manifest includes such things as the name of the assembly, its version number, type mapping information, and cultural settings.
  4. The second section is type metadata
  5. The type metadata is information about the data types.
  6. The type metadata aids in cross-language interoperability.
  7. The third part of an assembly is the program code stored in Microsoft Intermediate Language (MSIL) format.
  8. The fourth constituent of an assembly is the resources used by the program.

12.4.Assembly Load 12.4.1. Assemblies 12.4.2. <A href="/Tutorial/CSharp/0240__Assembly/differencebetweenAssemblyLoadandAssemblyLoadFrom.htm">difference between Assembly.Load and Assembly.LoadFrom</a> 12.4.3. <A href="/Tutorial/CSharp/0240__Assembly/LoadtypesclassesfromaAssemblyexefile.htm">Load types(classes) from a Assembly(exe file)</a> 12.4.4. <A href="/Tutorial/CSharp/0240__Assembly/LoadtheSystemXmlassemblyusinganAssemblyName.htm">Load the System.Xml assembly using an AssemblyName</a> 12.4.5. <A href="/Tutorial/CSharp/0240__Assembly/CreateTypebyAssemblyqualifedtypename.htm">Create Type by Assembly qualifed type name</a> 12.4.6. <A href="/Tutorial/CSharp/0240__Assembly/LateBinding.htm">Late Binding</a> 12.4.7. <A href="/Tutorial/CSharp/0240__Assembly/Assemblyunloading.htm">Assembly unloading</a> 12.4.8. <A href="/Tutorial/CSharp/0240__Assembly/Dynamicassemblyintrospection.htm">Dynamic assembly introspection</a> 12.4.9. <A href="/Tutorial/CSharp/0240__Assembly/DeeperReflectionListingAlltheTypesinanAssembly.htm">Deeper Reflection: Listing All the Types in an Assembly</a> 12.4.10. <A href="/Tutorial/CSharp/0240__Assembly/AssemblyLoader.htm">Assembly Loader</a> 12.4.11. <A href="/Tutorial/CSharp/0240__Assembly/GetManifestResourceStream.htm">GetManifestResourceStream</a>

Assembly Loader

using System;
using System.Reflection;
using System.IO;
public class AssemblyLoader
{
  private Assembly LoadedAssembly;
  public AssemblyLoader(string LoadedAssemblyName, bool PartialName)
  {
      Console.WriteLine(LoadedAssemblyName);
    if(PartialName == true)
      LoadedAssembly = Assembly.LoadWithPartialName(LoadedAssemblyName);
    else
      LoadedAssembly = Assembly.Load(LoadedAssemblyName);
    WritePropertiesToConsole();
  }
  private void WritePropertiesToConsole()
  {
    Console.WriteLine("Full Name: {0}", LoadedAssembly.FullName);
    Console.WriteLine("Location: {0}", LoadedAssembly.Location);
    Console.WriteLine("Code Base: {0}", LoadedAssembly.CodeBase);
    Console.WriteLine("Escaped Code Base: {0}", LoadedAssembly.EscapedCodeBase);
    Console.WriteLine("Loaded from GAC: {0}", LoadedAssembly.GlobalAssemblyCache);
  }
}
public class MainClass
{
  static void Main(string[] args)
  {
    AssemblyLoader Loader;
    Loader = new AssemblyLoader("System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false);
    Loader = new AssemblyLoader("System.Xml", false);
    Loader = new AssemblyLoader("System.Xml", true);
  }
}

Assembly unloading

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
public class MainClass
{
    public static void Main()
    {
        AppDomain ad = AppDomain.CreateDomain("IsolatedDLL");
        AppDomain.Unload(ad);
    }
}

Create Type by Assembly qualifed type name

using System;
using System.Text;
class MainClass
{
    public static void Main()
    {
        
        Type t5 = Type.GetType("System.Data.DataSet,System.Data," +
            "Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089");
    }
}

Deeper Reflection: Listing All the Types in an Assembly

using System;
using System.Reflection;
enum MyEnum
{
    Val1,
    Val2,
    Val3
}
class MyClass
{
}
struct MyStruct
{
}
class MainClass
{
    public static void Main(String[] args)
    {
        Assembly a = Assembly.LoadFrom (args[0]);
        Type[] types = a.GetTypes();
        
        foreach (Type t in types)
        {
            Console.WriteLine ("Name: {0}", t.FullName);
            Console.WriteLine ("Namespace: {0}", t.Namespace);
            Console.WriteLine ("Base Class: {0}", t.BaseType.FullName);
        }
    }
}

difference between Assembly.Load and Assembly.LoadFrom

using System;
using System.Reflection;
class Starter {
    static void Main() {
        Assembly library = Assembly.Load("library, Version=2.0.0.0, " +
          "Culture=Neutral, PublicKeyToken=9b184fc90fb9648d");
        Console.WriteLine("Assembly.Load:  {0}", library.FullName);
        library = Assembly.LoadFrom("library.dll");
        Console.WriteLine("Assembly.LoadFrom {0}", library.FullName);
    }
}

Dynamic assembly introspection

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
public class MainClass
{
    public static void Main()
    {
        int x = 10;
        Assembly a = Assembly.Load("mscorlib");
        Type t3 = a.GetType("System.Int32");
        
        Type t1 = typeof(int);
        Type t2 = x.GetType();
        Type t4 = Type.GetType("System.Int32");
        Console.WriteLine(t1 == t2);
        Console.WriteLine(t2 == t3);
        Console.WriteLine(t3 == t4);
    }
}
True
True
True

GetManifestResourceStream

using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
public class Loader {
    static Dictionary<string, Assembly> libs = new Dictionary<string, Assembly>();
    static void Main() {
        AppDomain.CurrentDomain.AssemblyResolve += FindAssem;
        Program.Go();
    }
    static Assembly FindAssem(object sender, ResolveEventArgs args) {
        string shortName = new AssemblyName(args.Name).Name;
        if (libs.ContainsKey(shortName)) return libs[shortName];
        using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Libs." + shortName + ".dll")) {
            byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);
            Assembly a = Assembly.Load(data);
            libs[shortName] = a;
            return a;
        }
    }
}
public class Program {
    public static void Go() {
    }
}

Late Binding

using System;
using System.Reflection;
using System.IO;
public class MainClass
{
  public static int Main(string[] args)
  {
    Assembly a = null;
    try
    {
      a = Assembly.Load("YourLibraryName");
    }
    catch(FileNotFoundException e)
    {Console.WriteLine(e.Message);}
  
    Type classType = a.GetType("YourLibraryName.ClassName");
    object obj = Activator.CreateInstance(classType);
  
    MethodInfo mi = classType.GetMethod("MethodName");
    mi.Invoke(obj, null);
    object[] paramArray = new object[2];    
    paramArray[0] = "Fred";
    paramArray[1] = 4;
    mi = classType.GetMethod("MethodName2");
    mi.Invoke(obj, paramArray);
    return 0;
  }
}

Load the System.Xml assembly using an AssemblyName

using System;
using System.Reflection;
using System.Globalization;
class MainClass
{
    public static void Main()
    {
        AssemblyName name2 = new AssemblyName();
        name2.Name = "System.Xml";
        name2.Version = new Version(2, 0, 0, 0);
        name2.CultureInfo = new CultureInfo("");    // Neutral culture.
        name2.SetPublicKeyToken( new byte[] {0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89});
        Assembly a2 = Assembly.Load(name2);
    }
}

Load types(classes) from a Assembly(exe file)

using System; 
 
class MyClass { 
  int x; 
  int y; 
 
  public MyClass(int i) { 
    Console.WriteLine("Constructing MyClass(int). "); 
    x = y = i;  
    show(); 
  } 
 
  public MyClass(int i, int j) { 
    Console.WriteLine("Constructing MyClass(int, int). "); 
    x = i; 
    y = j; 
    show(); 
  } 
 
  public int sum() { 
    return x+y; 
  } 
 
  public bool isBetween(int i) { 
    if((x < i) && (i < y)) return true; 
    else return false; 
  } 
 
  public void set(int a, int b) { 
    Console.Write("Inside set(int, int). "); 
    x = a; 
    y = b; 
    show(); 
  } 
 
  // Overload set. 
  public void set(double a, double b) { 
    Console.Write("Inside set(double, double). "); 
    x = (int) a; 
    y = (int) b; 
    show(); 
  } 
 
  public void show() { 
    Console.WriteLine("Values are x: {0}, y: {1}", x, y); 
  } 
} 
 
class AnotherClass { 
  string remark; 
 
  public AnotherClass(string str) { 
    remark = str; 
  } 
 
  public void show() { 
    Console.WriteLine(remark); 
  } 
} 
 
/////////////////////////////////////
using System; 
using System.Reflection; 
 
class MainClass { 
  public static void Main() { 
    int val; 
 
    Assembly asm = Assembly.LoadFrom("MyClasses.exe"); 
 
    Type[] alltypes = asm.GetTypes(); 
    foreach(Type temp in alltypes) 
      Console.WriteLine("Found: " + temp.Name); 
 
    Console.WriteLine(); 
 
  } 
}