我创建了一个虚拟DLL。我原以为我可以访问命名空间中的S1
。我可以看到我的函数,我可以在它的exe形式中看到带有il dasm的结构。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.Threading;
using System.Diagnostics.SymbolStore;
using System.IO;
namespace emitTest
{
class Program
{
static void Main(string[] args)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "HelloWorld";
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module;
module = assemblyBuilder.DefineDynamicModule("HelloWorld.exe", true);
TypeBuilder typeBuilder = module.DefineType("MyNamespace.HelloWorldType", TypeAttributes.Public | TypeAttributes.Class);
MethodBuilder methodbuilder = typeBuilder.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string[]) });
var s1 = module.DefineType("Space.S1", TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.SequentialLayout | TypeAttributes.BeforeFieldInit, typeof(System.ValueType));
s1.DefineField("a", typeof(int), FieldAttributes.Public);
s1.CreateType();
ILGenerator ilGenerator = methodbuilder.GetILGenerator();
ilGenerator.Emit(OpCodes.Ret);
Type helloWorldType = typeBuilder.CreateType();
if (false)
{
// set the entry point for the application and save it
assemblyBuilder.SetEntryPoint(methodbuilder, PEFileKinds.ConsoleApplication);
assemblyBuilder.Save("HelloWorld.exe");
}
else
{
assemblyBuilder.SetEntryPoint(methodbuilder, PEFileKinds.Dll);
assemblyBuilder.Save("HelloWorld.dll");
}
}
}
}
答案 0 :(得分:1)
我不确定我明白你究竟在问什么,但我认为问题在于你总是将模块定义为HelloWorld.exe
。您需要做的是确保模块名称与文件名匹配。
因此,如果要将程序集保存为HelloWorld.dll
,则需要将模块名称设置为HelloWorld.dll
。