C#动态创建对象过程

创建对象环境

  • 获取当前应用程序集引用的类库详细信息,动态类也将调用此类库

  obj类为项目动态编译时用到的模版类,主要提取其using信息用于动态生成的类使用

    1 AssemblyName[]refAss =Obj.GetType().Assembly.GetReferencedAssemblies();

   

  • 获取引用类库的本地路径

    1 String[]srtLocations refAss.Foreach(m =>m.Location).ToArray();

   

  • 配置编译参数

    1 CompilerParameters options new CompilerParameters();

    2 options.GenerateExecutable false;

    3 options.GenerateInMemory true;

    4 options.RefernecedAssemblies.AddRang(srtLocations);

   

编译

   

  • 创建C#语言编译器对象

  1 CodeDomProvider cSharpProvider CSharpCodeProvider.CreateProvider("CSarp");

   

  • 执行编译,并且返回编译结果

  source参数为包含using的完整C#代码

  1 CompilerResults results cSharpProvider.CompileAssemblyFromSource(options,source);

   

  • 获取编译错误列表 

    1 results.Errors.HasErrors;

   

获取对象实例

   

  • 获取编译的程序集

  1 Assembly dynamicAssembly results.CompiledAssembly;

   

  • 获取程序集中的成员

  1 Type type dynamicAssembly.GetTypes()[0];

   

  • 根据成员类型动态创建成员对象

  1 Object obj dynamicAssembly.CreateInstance(type.FullName);

   

posted @ 2014-08-06 09:34  liu0076  阅读(1622)  评论(0编辑  收藏  举报