C#在运行时动态创建类型的实现方法

 更新时间:2014年09月12日 10:46:58   投稿:shichen2014  
这篇文章主要介绍了C#在运行时动态创建类型的实现方法,主要通过动态生成C#代码再编译成程序集来实现动态创建类型的,需要的朋友可以参考下

本文实例讲述了C#在运行时动态创建类型的实现方法。是C#项目开发中很实用的技巧。分享给大家供大家参考。具体分析如下:

具体来说,C# 在运行时动态的创建类型是通过动态生成C#源代码,然后通过编译器编译成程序集的方式实现动态创建类型的

主要功能代码如下:

public static Assembly NewAssembly()
{
  //创建编译器实例。  
  provider = new CSharpCodeProvider();
  //设置编译参数。  
  cp = new CompilerParameters();
  cp.GenerateExecutable = false;
  cp.GenerateInMemory = true;

  // Generate an executable instead of 
  // a class library.
  //cp.GenerateExecutable = true;

  // Set the assembly file name to generate.
  cp.OutputAssembly = "c:\\1.dll";

  // Generate debug information.
  cp.IncludeDebugInformation = true;


  // Save the assembly as a physical file.
  cp.GenerateInMemory = false;

  // Set the level at which the compiler 
  // should start displaying warnings.
  cp.WarningLevel = 3;

  // Set whether to treat all warnings as errors.
  cp.TreatWarningsAsErrors = false;

  // Set compiler argument to optimize output.
  cp.CompilerOptions = "/optimize";

  cp.ReferencedAssemblies.Add("System.dll");
  //cp.ReferencedAssemblies.Add("System.Core.dll");
  cp.ReferencedAssemblies.Add("System.Data.dll");
  //cp.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
  cp.ReferencedAssemblies.Add("System.Deployment.dll");
  cp.ReferencedAssemblies.Add("System.Design.dll");
  cp.ReferencedAssemblies.Add("System.Drawing.dll");
  cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");

  //创建动态代码。  
  
  StringBuilder classSource = new StringBuilder();
  classSource.Append("using System;using System.Windows.Forms;\npublic  class  DynamicClass: UserControl \n");
  classSource.Append("{\n");
  classSource.Append("public DynamicClass()\n{\nInitializeComponent();\nConsole.WriteLine(\"hello\");}\n");
  classSource.Append( "private System.ComponentModel.IContainer components = null;\nprotected override void Dispose(bool disposing)\n{\n");
  classSource.Append( "if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);\n}\n");
  classSource.Append( "private void InitializeComponent(){\nthis.SuspendLayout();this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);");
  classSource.Append( "this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.Name = \"DynamicClass\";this.Size = new System.Drawing.Size(112, 74);this.ResumeLayout(false);\n}");
  //创建属性。  
  /*************************在这里改成需要的属性******************************/
  classSource.Append(propertyString("aaa"));
  classSource.Append(propertyString("bbb"));
  classSource.Append(propertyString("ccc"));

  classSource.Append("}");

  System.Diagnostics.Debug.WriteLine(classSource.ToString());
 
  //编译代码。  
  CompilerResults result = provider.CompileAssemblyFromSource(cp, classSource.ToString());
  if (result.Errors.Count > 0)
  {
 for( int i = 0; i < result.Errors.Count; i ++)
   Console.WriteLine(result.Errors[ i]);
 Console.WriteLine("error");
 return null;
  }
  
  //获取编译后的程序集。  
  Assembly assembly = result.CompiledAssembly;

  return assembly;
}

private static string propertyString(string propertyName)
{
  StringBuilder sbProperty = new StringBuilder();
  sbProperty.Append(" private  int  _" + propertyName + "  =  0;\n");
  sbProperty.Append(" public  int  " + "" + propertyName + "\n");
  sbProperty.Append(" {\n");
  sbProperty.Append(" get{  return  _" + propertyName + ";}  \n");
  sbProperty.Append(" set{  _" + propertyName + "  =  value;  }\n");
  sbProperty.Append(" }");
  return sbProperty.ToString();
}

希望本文所述对大家的C#程序设计有所帮助

相关文章

  • Unity3D实现摄像机镜头移动并限制角度

    Unity3D实现摄像机镜头移动并限制角度

    这篇文章主要为大家详细介绍了Unity3D实现摄像机镜头移动并限制角度,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-05-05
  • 深入解析C#中的abstract抽象类

    深入解析C#中的abstract抽象类

    这篇文章主要介绍了深入解析C#中的abstract抽象类,包括定义抽象类等C#面相对象编程中的基础知识,需要的朋友可以参考下
    2016-01-01
  • c#不使用系统api实现可以指定区域屏幕截屏功能

    c#不使用系统api实现可以指定区域屏幕截屏功能

    这篇文章主要介绍了不使用系统API通过纯c#实现屏幕指定区域截屏功能,截屏后还可以保存图象文件,大家参考使用吧
    2014-01-01
  • 详析C#的协变和逆变

    详析C#的协变和逆变

    这篇文章主要介绍了详析C#的协变和逆变,在引用类型系统时,协变、逆变和不变性具有如下定义。 这些示例假定一个名为 Base 的基类和一个名为 Derived的派生类,更多内容请需要的小伙伴参考下面文章内容
    2022-01-01
  • Unity ScrollView实现无限滑动效果

    Unity ScrollView实现无限滑动效果

    这篇文章主要为大家详细介绍了Unity ScrollView实现无限滑动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • C#基础之异步调用实例教程

    C#基础之异步调用实例教程

    这篇文章主要介绍了C#中的异步调用,对比同步调用分析了异步调用的原理及特点,并以实例形式给出了实现方法,需要的朋友可以参考下
    2014-09-09
  • 解析C#中的常量及如何在C#编程中定义常量

    解析C#中的常量及如何在C#编程中定义常量

    这篇文章主要介绍了C#中的常量及如何在C#编程中定义常量,是C#入门学习中的基础知识,需要的朋友可以参考下
    2016-01-01
  • C# Dictionary的使用实例代码

    C# Dictionary的使用实例代码

    C# Dictionary的使用实例代码,需要的朋友可以参考一下
    2013-04-04
  • C#通过反射打开相应窗体方法分享

    C#通过反射打开相应窗体方法分享

    本文章来给各位同学介绍关于C#单击菜单栏或工具栏时通过反射打开窗体的方法,有需要了解的朋友可进入参考参考。
    2015-05-05
  • C#中Span相关的性能优化建议

    C#中Span相关的性能优化建议

    Span 是C#7.2引入的一种新类型,在.NET Core 2.1运行时中受支持,Span 提供对内存连续区域的类型安全访问,这篇文章主要给大家介绍了关于C#中Span相关的一些性能优化建议,需要的朋友可以参考下
    2021-08-08

最新评论