0

我很难理解创建动态程序集,下面是一些代码:

public static void CreateMyAsm(AppDomain curAppDomain)
{
   AssemblyName assemblyName = new AssemblyName();
   assemblyName.Name = "MyAssembly";
   assemblyName.Version = new Version("1.0.0.0");
   AssemblyBuilder assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
   ModuleBuilder module =
   assembly.DefineDynamicModule("zMyAssembly", "zMyAssembly.dll");
   TypeBuilder helloWorldClass = module.DefineType("zMyAssembly.HelloWorld", TypeAttributes.Public);

  /*
   ...configure ConstructorBuilder, FieldBuilder, MethodBuilder  etc with ILGenerator.Emit() here

  ConstructorBuilder constructor = helloWorldClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, constructorArgs);
  ILGenerator constructorIL = constructor.GetILGenerator();
  ...
  FieldBuilder msgField = helloWorldClass.DefineField("theMessage", Type.GetType("System.String"),FieldAttributes.Private);
  constructorIL.Emit(OpCodes.Stfld, msgField);
  */  
   helloWorldClass.CreateType();
   assembly.Save("MyAssembly.dll");
}

所以我的问题是,为什么我们需要调用helloWorldClass.CreateType();来创建一个类型?

因为我们通常会在 main 方法中得到一个类型:

static void Main(string[] args)
{
   ...
   Type t = Type.GetType("MyAssembly.HelloWorld, MyAssembly");
   ...
}

所以我们可以动态获取类型?

编辑:有人说Type.GetType 返回现有的元数据。AssemblyBuilder.CreateType 引入了新的元数据。

所以所有的TypeBuilder.DefineMethod,TypeBuilder.DefineField等都TypeBuilder.DefineConstructor不会“引入”元数据?在旅途中自动调用“写入”或“引入”元数据不是更明智TypeBuilder.DefineXXX,因此不再需要 AssemblyBuilder.CreateType() 吗?

4

0 回答 0