0

我创建了一个虚拟 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");
            }
        }
    }
}
4

1 回答 1

1

我不确定我理解你到底在问什么,但我认为问题在于你总是将模块定义为HelloWorld.exe. 您需要做的是确保模块名称与文件名匹配。

因此,如果要将程序集另存为HelloWorld.dll,则还需要将模块名称设置为HelloWorld.dll

于 2013-03-11T08:08:12.680 回答