Csharp/C Sharp/Reflection/Assembly

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

AssemblyCulture AssemblyVersion

 
using System;
using System.Reflection;
[assembly:AssemblyCulture("")]
[assembly:AssemblyVersion("1.1.0.5")]
namespace MainClass
{
    class MainClass
    {
        public static void Main()
        {
            Console.WriteLine("\nMain method complete. Press Enter.");
        }
    }
}


AssemblyName: Name, Version, CultureInfo, SetPublicKeyToken

 
using System;
using System.Reflection;
using System.Globalization;
    class MainClass
    {
        public static void ListAssemblies()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
            foreach (Assembly a in assemblies)
            {
                Console.WriteLine(a.GetName());
            }
        }
        public static void Main()
        {
            ListAssemblies();
            string name1 = "System.Data, Version=2.0.0.0," +"Culture=neutral, PublicKeyToken=b77a5c561934e089";
            Assembly a1 = Assembly.Load(name1);
            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);
            Assembly a3 = Assembly.Load("SomeAssembly");
            Assembly a4 = Assembly.LoadFrom(@"c:\shared\MySharedAssembly.dll");
            Console.WriteLine("\n\n**** AFTER ****");
            ListAssemblies();
        }
    }


Create assembly

using System;
using System.Reflection;
using System.Reflection.Emit;
class CodeGenerator {       
    Type t;
    public static void Main() {
       CodeGenerator codeGen = new CodeGenerator();
       Type t = codeGen.T;
       if (t != null) {
          object o = Activator.CreateInstance(t);
          MethodInfo helloWorld = t.GetMethod("HelloWorld");
          if (helloWorld != null) {
             // Run the HelloWorld Method
             helloWorld.Invoke(o, null);
          } else {
             Console.WriteLine("Could not retrieve MethodInfo");
          }
       } else {
             Console.WriteLine("Could not access the Type");
       }
    } 
    public CodeGenerator() {
       AppDomain currentDomain = AppDomain.CurrentDomain;
       AssemblyName assemName = new AssemblyName();
       assemName.Name = "MyAssembly";
       AssemblyBuilder assemBuilder = currentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run);
       ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("MyModule");
       TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass",TypeAttributes.Public);
       MethodBuilder methodBuilder = typeBuilder.DefineMethod("HelloWorld", MethodAttributes.Public,null,null);
       ILGenerator msilG = methodBuilder.GetILGenerator();
       msilG.EmitWriteLine("www.nfex.ru");
       msilG.Emit(OpCodes.Ret);
       t = typeBuilder.CreateType();
   }
   public Type T {
       get { 
         return this.t;
       }
   }
}


CurrentDomain, GetAssemblies

 

using System;
using System.Reflection;
using System.Globalization;
class MainClass
{
    public static void Main()
    {
        ListAssemblies();
        string name1 = "System.Data, Version=2.0.0.0," +"Culture=neutral, PublicKeyToken=b77a5c561934e089";
        Assembly a1 = Assembly.Load(name1);
        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);
        Assembly a3 = Assembly.Load("SomeAssembly");
        Assembly a4 = Assembly.LoadFrom(@"c:\shared\MySharedAssembly.dll");
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
        foreach (Assembly a in assemblies)
        {
            Console.WriteLine(a.GetName());
        }
    }
}


Dynamically invoking methods from classes in an assembly.

 

using System;
using System.Reflection;
interface IMyInterface {
    void PrintAString(string s);
    void PrintAnInteger(int i);
    void PrintSomeNumbers(string desc, int i, double d);
    int GetANumber(string s);
}
public class MyClass : IMyInterface {
    public MyClass() {
    }
    public void PrintAString(string s) {
        Console.WriteLine("PrintAString: {0}", s);
    }
    public void PrintAnInteger(int i) {
        Console.WriteLine("PrintAnInteger: {0}", i);
    }
    public void PrintSomeNumbers(string desc, int i, double d) {
        Console.WriteLine("PrintSomeNumbers String: {0}", desc);
        Console.WriteLine("Integer: {0}", i);
        Console.WriteLine("Double: {0}", d);
    }
    public int GetANumber(string s) {
        Console.WriteLine("GetANumber: {0}", s);
        return 99;
    }
    public int DoItAll(string s, int i, double d) {
        IMyInterface mi = (IMyInterface)this;
        mi.PrintSomeNumbers(s, i, d);
        return mi.GetANumber(s);
    }
}
public class MainClass {
    public static void DoDynamicInvocation(string assembly) {
        Assembly a = Assembly.LoadFrom(assembly);
        foreach (Type t in a.GetTypes()) {
            if (t.IsClass == false)
                continue;
            if (t.GetInterface("IMyInterface") == null)
                continue;
            Console.WriteLine("Creating instance of class {0}", t.FullName);
            object obj = Activator.CreateInstance(t);
            object[] args = { "Dynamic", 1, 99.6 };
            object result;
            result = t.InvokeMember("DoItAll",BindingFlags.Default|BindingFlags.InvokeMethod,null,obj,args);
            Console.WriteLine("Result of dynamic call: {0}", result);
            object[] args2 = { 12 };
            t.InvokeMember("PrintAnInteger",BindingFlags.Default | BindingFlags.InvokeMethod,null,obj,args2);
        }
    }
    public static void Main(string[] args) {
        MyClass dmi = new MyClass();
        dmi.PrintSomeNumbers("PrintMe", 1, 1.9);
        int i = dmi.GetANumber("GiveMeOne");
        Console.WriteLine("I = {0}", i);
        DoDynamicInvocation(args[0]);
    }
}


Examining Location Information

using System;
using System.Reflection;
   
public class MainClass
{
    static void Main()
    {
        Assembly EntryAssembly;
   
        EntryAssembly = Assembly.GetEntryAssembly();
        Console.WriteLine("Location: {0}", EntryAssembly.Location);
        Console.WriteLine("Code Base: {0}", EntryAssembly.CodeBase);
        Console.WriteLine("Escaped Code Base: {0}", EntryAssembly.EscapedCodeBase);
        Console.WriteLine("Loaded from GAC: {0}", EntryAssembly.GlobalAssemblyCache);
    }
}


Find Attribytes from assembly name

using System;
using System.Reflection;
public class FindAttributes {
  static void Main(string[] args) {
      String assemblyName = "test.exe" ;
      try
      {
        Assembly  a = Assembly.LoadFrom ( assemblyName ) ;
        object[]  attributes = a.GetCustomAttributes( true ) ;
        if ( attributes.Length > 0 ) {
          Console.WriteLine ( "Assembly attributes for "{0}"..." , assemblyName ) ;
          foreach ( object o in attributes )
            Console.WriteLine ( "  {0}" , o.ToString ( ) ) ;
        }
        else{
          Console.WriteLine ( "Assembly {0} contains no Attributes." , assemblyName ) ;
        } 
      } catch ( Exception ex ) {
        Console.WriteLine ( ex.ToString ( ) ) ;
      }
  }
}


Finding and Creating Assembly Types

using System;
using System.Reflection;
   
public class MainClass
{
    static void Main(string[] args)
    {
        Assembly XMLAssembly;
        Type[] XMLTypes;
   
        XMLAssembly = Assembly.Load("System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
        XMLTypes = XMLAssembly.GetExportedTypes();
        foreach(Type XMLType in XMLTypes) {
            object NewObject;
            try {
                Console.Write(XMLType.ToString());
                NewObject = XMLAssembly.CreateInstance(XMLType.ToString());
                if(NewObject != null)
                    Console.WriteLine(" - Creation successful");
                else
                    Console.WriteLine(" - CREATION ERROR");
            } catch(Exception e) {
                Console.WriteLine(" - EXCEPTION: {0}", e.Message);
            }
        }
    }
}


Get current application domain

    using System;
  using System.Reflection;
  using System.Windows.Forms;
    public class MyAppDomain
    {
        public static void Main(string[] args)
        {
      AppDomain ad = AppDomain.CurrentDomain;
      Assembly[] loadedAssemblies = ad.GetAssemblies();
      
      Console.WriteLine("Here are the assemblies loaded in this appdomain\n");
      foreach(Assembly a in loadedAssemblies)
      {
        Console.WriteLine(a.FullName);
      }
        }
    }


GetReferencedAssemblies

 
using System;
using System.Reflection;
public class MainClass
{
    static void Main()
    {
    Assembly EntryAssembly;
    EntryAssembly = Assembly.GetEntryAssembly();
    foreach(AssemblyName Name in EntryAssembly.GetReferencedAssemblies())
      Console.WriteLine("Name: {0}", Name.ToString());
    }
}


List All Members from an Assembly

using System;
using System.Reflection;

public class Test
{
    public static void Main(string[] args)
    {
    Assembly a = null;
        AssemblyName asmName;
      asmName = new AssemblyName();
      asmName.Name = "Test";
      Version v = new Version("1.0.454.30104");
      asmName.Version = v;
 
        a = Assembly.Load(asmName);
    Type test = a.GetType("Test");
  
    Console.WriteLine("Listing all members for {0}", test);
    MemberInfo[] mi = test.GetMembers();
    foreach(MemberInfo m in mi)
      Console.WriteLine("Type {0}: {1} ",
          m.MemberType.ToString(), m);
    }
}


List All Types from an Assembly

using System;
using System.Reflection;
public class Test
{
    public static void Main(string[] args)
    {
    Assembly a = null;
        AssemblyName asmName;
      asmName = new AssemblyName();
      asmName.Name = "Test";// Test.exe
      Version v = new Version("1.0.454.30104");
      asmName.Version = v;
 
        a = Assembly.Load(asmName);
    Console.WriteLine("Listing all types in {0}", a.FullName);
    Type[] types = a.GetTypes();
    foreach(Type t in types)
      Console.WriteLine("Type: {0}", t);
    }
}


Load assembly from namespace System.Xml

 

using System;
using System.Reflection;
using System.Globalization;
    class MainClass
    {
        public static void ListAssemblies()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
            foreach (Assembly a in assemblies)
            {
                Console.WriteLine(a.GetName());
            }
        }
        public static void Main()
        {
            ListAssemblies();
            string name1 = "System.Data, Version=2.0.0.0," +"Culture=neutral, PublicKeyToken=b77a5c561934e089";
            Assembly a1 = Assembly.Load(name1);
            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);
            Assembly a3 = Assembly.Load("SomeAssembly");
            Assembly a4 = Assembly.LoadFrom(@"c:\shared\MySharedAssembly.dll");
            Console.WriteLine("\n\n**** AFTER ****");
            ListAssemblies();
        }
    }


Loading Assemblies Dynamically with Load() and LoadWithPartialName()

using System;
using System.Reflection;
using System.IO;
   
public class MainClass
{
    static void Main(string[] args)
    {
        AssemblyLoader("System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false);
        AssemblyLoader("System.Xml", false);
        AssemblyLoader("System.Drawing", true);
    }
    public static void AssemblyLoader(string LoadedAssemblyName, bool PartialName)
    {
        try
        {
            Assembly LoadedAssembly;
            Console.WriteLine("| Loading Assembly {0}", LoadedAssemblyName);
            if(PartialName == true)
                LoadedAssembly = Assembly.LoadWithPartialName(LoadedAssemblyName);
            else
                LoadedAssembly = Assembly.Load(LoadedAssemblyName);
            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);
        } catch(FileNotFoundException) {
            Console.WriteLine("EXCEPTION: Cannot load assembly.");
        }
    }
}


Location of Assembly

 
using System;
using System.Reflection;
public class MainClass {
    static void Main() {
        Assembly EntryAssembly;
        EntryAssembly = Assembly.GetEntryAssembly();
        Console.WriteLine("Location: {0}", EntryAssembly.Location);
        Console.WriteLine("Code Base: {0}", EntryAssembly.CodeBase);
        Console.WriteLine("Escaped Code Base: {0}", EntryAssembly.EscapedCodeBase);
        Console.WriteLine("Loaded from GAC: {0}", EntryAssembly.GlobalAssemblyCache);
    }
}


new AssemblyName()

 
using System;
using System.Reflection;
using System.Collections.Generic;
class MainClass
{
    public static void Main(string[] args)
    {
        AssemblyName assembly1 = new AssemblyName("com.microsoft.crypto, Culture=en, PublicKeyToken=a5d015c7d5a0b012, Version=1.0.0.0"); 
        Dictionary<string, AssemblyName> assemblyDictionary = new Dictionary<string, AssemblyName>();
        assemblyDictionary.Add("Crypto", assembly1);
        AssemblyName ass1 = assemblyDictionary["Crypto"];
        Console.WriteLine("Got AssemblyName from dictionary: {0}", ass1);
        List<AssemblyName> assemblyList = new List<AssemblyName>();
        assemblyList.Add(assembly1);
        AssemblyName ass2 = assemblyList[0];
        Console.WriteLine("\nFound AssemblyName in list: {0}", ass1);
        Stack<AssemblyName> assemblyStack = new Stack<AssemblyName>();
        assemblyStack.Push(assembly1);
        AssemblyName ass3 = assemblyStack.Pop();
        Console.WriteLine("\nPopped AssemblyName from stack: {0}", ass1);
     }
}


Retrieving a List of Referenced Assemblies

using System;
using System.Reflection;
   
public class MainClass
{
    static void Main()
    {
        Assembly EntryAssembly;
   
        EntryAssembly = Assembly.GetEntryAssembly();
        foreach(AssemblyName Name in EntryAssembly.GetReferencedAssemblies()){
            Console.WriteLine("Name: {0}", Name.ToString());
        }    
    }
}


Set AssemblyTitle, AssemblyDescription, AssemblyConfiguration, AssemblyCompany, AssemblyProduct

 
using System.Reflection;
using System.Windows.Forms;
   
[assembly: AssemblyTitle("title")]
[assembly: AssemblyDescription("code.")]
[assembly: AssemblyConfiguration("Retail")]
[assembly: AssemblyCompany("Inc.")]
[assembly: AssemblyProduct("C#")]
[assembly: AssemblyCopyright("Inc.")]
[assembly: AssemblyVersion("1.0.*")]
   
public class SimpleHelloWorld : Form
{
    public static void Main()
    {
        Application.Run(new SimpleHelloWorld());
    }
   
    public SimpleHelloWorld()
    {
        Text = "Hello, WindowsForms!";
    }
}


Simple Windows Form Application with Version Information

using System.Reflection;
using System.Windows.Forms;
   
[assembly: AssemblyTitle("This is the title")]
[assembly: AssemblyDescription("This is the description")]
[assembly: AssemblyConfiguration("Here is for the configuration")]
[assembly: AssemblyCompany("Demo 2s, Inc.")]
[assembly: AssemblyProduct("C# Demo")]
[assembly: AssemblyCopyright("(c) 2002 Demo2s, Inc.")]
[assembly: AssemblyVersion("1.0.*")]
   
public class SimpleHelloWorld : Form
{
    public static void Main()
    {
        Application.Run(new SimpleHelloWorld());
    }
   
    public SimpleHelloWorld()
    {
        Text = "Hello, WindowsForms!";
    }
}


Use Assembly to indicate the version and culture

using System;
using System.Reflection;
[assembly:AssemblyCulture("")]
[assembly:AssemblyVersion("1.1.0.5")]
class Test{
   public static void Main() {
       Console.WriteLine("www.nfex.ru");
   }
}


Working with an Assembly Entry Point

using System;
using System.Reflection;
   
public class MainClass
{
    static void Main(string[] args)
    {
        Assembly EntryAssembly = Assembly.GetEntryAssembly();
        if(EntryAssembly.EntryPoint == null){
            Console.WriteLine("The assembly has no entry point.");
        }else{
            Console.WriteLine(EntryAssembly.EntryPoint.ToString());
        }
    }
}