C#原码动态编译功能实现之方法二~

本文介绍了C#原码动态编译功能实现的方法二。给出了相关代码,包括创建CSharpCodeProvider、设置CompilerParameters等,还给出了测试原码示例,可实现将当前时间写入指定文件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://ms.mblogger.cn/minbear/posts/2530.aspx

 

C#原码动态编译功能实现之方法二~

using Microsoft.CSharp;
using System.CodeDom.Compiler;

 

   CSharpCodeProvider _SCP = new CSharpCodeProvider();
   CompilerParameters _CP = new CompilerParameters();

   _CP.GenerateExecutable = false;
   _CP.MainClass = "CodeCompile.RunExpression";

   _CP.OutputAssembly = "RunExpression.dll";

   _CP.IncludeDebugInformation = true;

   _CP.ReferencedAssemblies.Add( "System.dll" );

   _CP.GenerateInMemory = false;

   _CP.WarningLevel = 3;

   _CP.TreatWarningsAsErrors = false;
   
   _CP.CompilerOptions = "/optimize";
   _CP.TempFiles = new TempFileCollection("..", true);

   _SCP.CreateCompiler().CompileAssemblyFromSource(_CP,this.txtCodeContent.Text);

 

//注:this.txtCodeContent.Text即为原代码内容,我的测试原码如下:

using System;
using System.IO;

namespace CodeCompile
{
 ///


 /// RunExpression 的摘要说明。
 ///

 public class RunExpression
 {
  public RunExpression()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  public void Run()
  {
   int i = 0;
   int j = 1;

   int m = i + j;

   System.IO.StreamWriter _FS = new System.IO.StreamWriter(@"E:/1.txt",true);
   _FS.Write(System.DateTime.Now.ToString("yyyy-MM-dd mm:ss"));
   _FS.Close();
   
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值