从动态生成的程序集中引用GAC程序集需要以下步骤:
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("MyDynamicAssembly"),
AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("MyDynamicModule", "MyDynamicAssembly.dll");
TypeBuilder tb = mb.DefineType("MyDynamicType", TypeAttributes.Public);
MethodBuilder methBuilder = tb.DefineMethod("MyDynamicMethod",
MethodAttributes.Public | MethodAttributes.Static,
typeof(void),
Type.EmptyTypes);
ILGenerator il = methBuilder.GetILGenerator();
Emit
方法引用GAC程序集中的类型:Type gacType = Type.GetType("GacAssembly.MyNamespace.MyType, GacAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<your_public_key_token>");
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Call, gacType.GetMethod("MyMethod"));
il.Emit(OpCodes.Ret);
Type dynamicType = tb.CreateType();
ab.Save("MyDynamicAssembly.dll");
MyDynamicMethod
方法:Assembly.LoadFrom("MyDynamicAssembly.dll").GetType("MyDynamicType").GetMethod("MyDynamicMethod").Invoke(null, null);
这样,你就可以从动态生成的程序集中引用GAC程序集了。
领取专属 10元无门槛券
手把手带您无忧上云