这个是网上看到的一段代码,利用反射创建了一个程序集,很强大。

    1. using System;
    2. using System;
    3. using System.Reflection;
    4. using System.Reflection.Emit;
    5. using System.Threading;
    6. namespace DynamicDLL
    7. {
    8. class Program
    9. {
    10. static void Main(string[] args)
    11. {
    12. // Create an assembly.
    13. AssemblyName myAssemblyName = new AssemblyName();
    14. myAssemblyName.Name = "SampleAssembly";
    15. AssemblyBuilder myAssembly =Thread.GetDomain().DefineDynamicAssembly(myAssemblyName,AssemblyBuilderAccess.RunAndSave);
    16. // Create a module. For a single-file assembly the module
    17. // name is usually the same as the assembly name.
    18. ModuleBuilder myModule =myAssembly.DefineDynamicModule(myAssemblyName.Name,myAssemblyName.Name + ".dll", true);
    19. // Define a public class 'Example'.
    20. TypeBuilder myTypeBuilder =myModule.DefineType("Example", TypeAttributes.Public);
    21. // Create the 'Function1' public method, which takes an integer
    22. // and returns a string.
    23. MethodBuilder myMethod = myTypeBuilder.DefineMethod("Function1",MethodAttributes.Public | MethodAttributes.Static,typeof(String), new Type[] {typeof(int) });
    24. // Generate IL for 'Function1'. The function body demonstrates
    25. // assigning an argument to a local variable, assigning a
    26. // constant string to a local variable, and putting the contents
    27. // of local variables on the stack.
    28. ILGenerator myMethodIL = myMethod.GetILGenerator();
    29. // Create local variables named myString and myInt.
    30. LocalBuilder myLB1 = myMethodIL.DeclareLocal(typeof(string));
    31. myLB1.SetLocalSymInfo("myString");
    32. Console.WriteLine("local'myString'type is: {0}", myLB1.LocalType);
    33. LocalBuilder myLB2 = myMethodIL.DeclareLocal(typeof(int));
    34. myLB2.SetLocalSymInfo("myInt", 1, 2);
    35. Console.WriteLine("local'myInt'type is: {0}", myLB2.LocalType);
    36. // Store the function argument in myInt.
    37. myMethodIL.Emit(OpCodes.Ldarg_0);
    38. myMethodIL.Emit(OpCodes.Stloc_1);
    39. // Store a literal value in myString, and return the value.
    40. myMethodIL.Emit(OpCodes.Ldstr, "string value");
    41. myMethodIL.Emit(OpCodes.Stloc_0);
    42. myMethodIL.Emit(OpCodes.Ldloc_0);
    43. myMethodIL.Emit(OpCodes.Ret);
    44. // Create "Example" class.
    45. Type myType1 = myTypeBuilder.CreateType();
    46. Console.WriteLine("'Example' is created.");
    47. myAssembly.Save(myAssemblyName.Name + ".dll");
    48. Console.WriteLine("'{0}' is created.", myAssemblyName.Name +".dll");
    49. // Invoke 'Function1' method of 'Example', passing the value 42.
    50. Object myObject2 = myType1.InvokeMember("Function1",BindingFlags.InvokeMethod, null, null, new Object[] {42});
    51. Console.WriteLine("Example.Function1 returned: {0}", myObject2);
    52. }
    53. }
    54. }