Dynamic creation assembly

xiaoxiao2021-03-05  19

using System; using System.Reflection; using System.Threading; using System.Reflection.Emit; namespace TestDriver {public interface ISayHello {int SayHello ();} public class ReflectionTest {private Assembly EmitAssembly (string sMsg) {AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "SayHelloAssembly"; AssemblyBuilder newAssembly = Thread.GetDomain () DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Run);. ModuleBuilder newModule = newAssembly.DefineDynamicModule ( "SayHello"); TypeBuilder myType = newModule.DefineType ( "MySayHello ", TypeAttributes.Public | TypeAttributes.Class); myType.AddInterfaceImplementation (typeof (iSayHello)); Type [] paramTypes = new Type [0]; Type returnType = typeof (int); MethodBuilder simpleMethod = myType.DefineMethod (" SayHello " Methodattributes.public | method, returntype, paramtypes; ilgenerator generator = SimpleMethod.getilGenerator (); generator.emitwriteline ("Hello" smsg); // Writing code GEN erator.Emit (OpCodes.Ldc_I4,1); // stack generator.Emit (OpCodes.Ret); // return stack MethodInfo sayHelloInfo = typeof (ISayHello) .GetMethod ( "SayHello"); myType.DefineMethodOverride (simpleMethod, SayHelloInfo; // specify the method to overload mytype.createtype (); // Create Type Return newassembly;} public int dosayhello (STRING SMSG) {if (SayHello == Null) {generatecode (SMSG);} return (Sayhello.sayhello) ());} public void GenerateCode (string sMsg) {Assembly theAssembly = EmitAssembly (sMsg); sayHello = (iSayHello) theAssembly.CreateInstance ( "MySayHello");} private iSayHello sayHello;

转载请注明原文地址:https://www.9cbs.com/read-36810.html

New Post(0)