动态生成和编译源代码


// 以前遇到不熟悉的属性或函数时,我会新建一个控制台程序,然后写要测试的属性或函数,然后编译在Concle中查看,感觉挺麻烦,于是写了下面这段代码,可以输入你的一些想测试的代码,然后显示出来,感觉方便多了。

// 动态生成和编译源代码
using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.IO;

namespace cjl
{
 public delegate string Run();
 
 public class Form1 : System.Windows.Forms.Form
 {
  Run run;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.Button RunCode;
  private System.Windows.Forms.TextBox Code;
  private System.Windows.Forms.Label Result;
  private System.Windows.Forms.TextBox CodeOutput;
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   InitializeComponent();
  }

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code

  private void InitializeComponent()
  {
   this.RunCode = new System.Windows.Forms.Button();
   this.Code = new System.Windows.Forms.TextBox();
   this.Result = new System.Windows.Forms.Label();
   this.label2 = new System.Windows.Forms.Label();
   this.CodeOutput = new System.Windows.Forms.TextBox();
   this.SuspendLayout();
   //
   // RunCode
   //
   this.RunCode.Location = new System.Drawing.Point(40, 104);
   this.RunCode.Name = "RunCode";
   this.RunCode.Size = new System.Drawing.Size(336, 23);
   this.RunCode.TabIndex = 1;
   this.RunCode.Text = "运行代码";
   this.RunCode.Click += new System.EventHandler(this.button1_Click);
   //
   // Code
   //
   this.Code.Location = new System.Drawing.Point(40, 16);
   this.Code.Multiline = true;
   this.Code.Name = "Code";
   this.Code.Size = new System.Drawing.Size(336, 80);
   this.Code.TabIndex = 2;
   this.Code.Text = "// 最后一句必须return字符串类型 /r/nint i = 2;/r/nstring s = /"ssss/";/r/nreturn string.Concat(i, s);";
   //
   // Result
   //
   this.Result.Location = new System.Drawing.Point(40, 136);
   this.Result.Name = "Result";
   this.Result.Size = new System.Drawing.Size(336, 160);
   this.Result.TabIndex = 3;
   this.Result.Text = "显示结果";
   //
   // label2
   //
   this.label2.Location = new System.Drawing.Point(0, 24);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(32, 23);
   this.label2.TabIndex = 4;
   this.label2.Text = "代码";
   //
   // CodeOutput
   //
   this.CodeOutput.Location = new System.Drawing.Point(384, 16);
   this.CodeOutput.Multiline = true;
   this.CodeOutput.Name = "CodeOutput";
   this.CodeOutput.Size = new System.Drawing.Size(320, 288);
   this.CodeOutput.TabIndex = 5;
   this.CodeOutput.Text = "";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(712, 317);
   this.Controls.AddRange(new System.Windows.Forms.Control[] {
                    this.CodeOutput,
                    this.label2,
                    this.Result,
                    this.Code,
                    this.RunCode});
   this.Name = "Form1";
   this.Text = "Form1";
   this.ResumeLayout(false);

  }
  #endregion

  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   
   if (this.Code.Text.LastIndexOf("return ") < 0)
   {
    string message = "必须包含reuturn,并且返回的类型是string类型。";
    MessageBox.Show(message);
    Result.Text = message;
    return;
   }

   CSharpCodeProvider codeProvider = new CSharpCodeProvider();
   ICodeGenerator codeGenerator = codeProvider.CreateGenerator();

   CodeNamespace ns = new CodeNamespace("cjl");
   ns.Comments.Add(new CodeCommentStatement("名称空间注释"));

   // 如果在运行时出现错误,有可能你所输入的代码在其它名称空间中,请在此加入更多CodeNamespaceImport
   ns.Imports.Add(new CodeNamespaceImport("System"));
   ns.Imports.Add(new CodeNamespaceImport("System.IO"));

   CodeTypeDeclaration testClass = new CodeTypeDeclaration("Test");
   testClass.TypeAttributes = TypeAttributes.Public;
   testClass.IsClass = true;
   ns.Types.Add(testClass);

   CodeMemberMethod function = new CodeMemberMethod();
   function.Attributes = MemberAttributes.Public;
   function.Name = "Try";
   function.ReturnType = new CodeTypeReference(typeof(string));

   foreach (string s in this.Code.Text.Split(';'))
   {
    function.Statements.Add(new CodeSnippetStatement(s + ";"));
   }

   
   testClass.Members.Add(function);
   
   // 写入文件
   TextWriter writer = new StreamWriter(new FileStream("Temp.cs", FileMode.Create));
   CodeGeneratorOptions options = new CodeGeneratorOptions();
   options.BracingStyle = "C";
   codeGenerator.GenerateCodeFromNamespace(ns, writer, options);
   writer.Close();

 
   CodeOutput.Text = new StreamReader(new FileStream("Temp.cs", FileMode.Open)).ReadToEnd();


   CodeCompileUnit compileUnit = new CodeCompileUnit();
   compileUnit.Namespaces.Add(ns);
   
   CompilerParameters compilerParameters = new CompilerParameters();
   compilerParameters.GenerateInMemory=true;
   
   ICodeCompiler csharpCompiler = codeProvider.CreateCompiler();
   CompilerResults compilerResults = csharpCompiler.CompileAssemblyFromDom(compilerParameters,compileUnit);
   if ( compilerResults != null && compilerResults.Errors.Count > 0 )
   {
    foreach( CompilerError err in compilerResults.Errors )
    {
     Result.Text = err.ToString() + "/n";
    }
   }
         
   object o = compilerResults.CompiledAssembly.CreateInstance("cjl.Test",true);
   run = (Run) Delegate.CreateDelegate(typeof(Run), o, function.Name);
 
   this.Result.Text = "运行以上代码结果如下:/n/n" + run();
  }
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++的STL中实现由一个bitset类模板,其用法如下: std::bitset bs; 也就是说,这个bs只能支持64位以内的位存储和操作;bs一旦定义就不能动态增长了。本资源附件中实现了一个动态Bitset,和标准bitset兼容。 /** @defgroup Bitset Bitset位集类 * @{ */ //根据std::bitset改写,函数意义和std::bitset保持一致 class CORE_API Bitset: public Serializable { typedef typename uint32_t _Ty; static const int _Bitsperword = (CHAR_BIT * sizeof(_Ty)); _Ty * _Array; //最低位放在[0]位置,每位的默认值为0 int _Bits;//最大有效的Bit个数 private: int calculateWords()const; void tidy(_Ty _Wordval = 0); void trim(); _Ty getWord(size_t _Wpos)const; public: //默认构造 Bitset(); //传入最大的位数,每位默认是0 Bitset(int nBits); virtual ~Bitset(); //直接整数转化成二进制,赋值给Bitset,最高低放在[0]位置 Bitset(unsigned long long _Val); //拷贝构造函数 Bitset(const Bitset & b); Bitset(const char * str); Bitset(const std::string & str, size_t _Pos, size_t _Count); public: size_t size()const; //返回设置为1的位数 size_t count() const; bool subscript(size_t _Pos) const; bool get(size_t pos) const; //设置指定位置为0或1,true表示1,false表示0,如果pos大于数组长度,则自动扩展 void set(size_t _Pos, bool _Val = true); //将位数组转换成整数,最低位放在[0]位置 //例如数组中存放的1011,则返回13,而不是返回11 unsigned long long to_ullong() const; bool test(size_t _Pos) const; bool any() const; bool none() const; bool all() const; std::string to_string() const; public: //直接整数转化成二进制,赋值给Bitset,最高位放在[0]位置 Bitset& operator = (const Bitset& b); //直接整数转化成二进制,赋值给Bitset,最高位放在[0]位置 Bitset& operator = (unsigned long long ull); //返回指定位置的值,如果pos大于位数组长度,自动拓展 bool operator [] (const size_t pos); //测试两个Bitset是否相等 bool operator == (const Bitset & b); bool operator != (const Bitset & b); Bitset operator<>(size_t _Pos) const; bool operator > (const Bitset & c)const; bool operator < (const Bitset & c)const; Bitset& operator &=(const Bitset& _Right); Bitset& operator|=(const Bitset& _Right); Bitset& operator^=(const Bitset& _Right); Bitset& operator<>=(size_t _Pos); public: Bitset& flip(size_t _Pos); Bitset& flip(); //将高位与低位互相,如数组存放的是1011,则本函数执行后为1101 Bitset& reverse(); //返回左边n位,构成新的Bitset Bitset left(size_t n) const; //返回右边n位,构成新的Bitset Bitset right(size_t n) const; //判断b包含的位数组是否是本类的位数组的自串,如果是返回开始位置 size_t find (const Bitset & b) const; size_t find(unsigned long long & b) const; size_t find(const char * b) const; size_t find(const std::string & b) const; //判断本类的位数组是否是b的前缀 bool is_prefix(unsigned long long & b) const; bool is_prefix(const char * b) const; bool is_prefix(const std::string & b) const; bool is_prefix(const Bitset & b) const; void clear(); void resize(size_t newSize); void reset(const unsigned char * flags, size_t s); void reset(unsigned long long _Val); void reset(const char * _Str); void reset(const std::string & _Str, size_t _Pos, size_t _Count); //左移动n位,返回新的Bitset //extendBits=false "1101" 左移动2位 "0100"; //extendBits=true "1101" 左移动2位 "110100"; Bitset leftShift(size_t n,bool extendBits=false)const; //右移动n位,返回新的Bitset //extendBits=false "1101" 右移动2位 "0011"; //extendBits=true "1101" 右移动2位 "001101"; Bitset rightShift(size_t n, bool extendBits = false) const; public: virtual uint32_t getByteArraySize(); // returns the size of the required byte array. virtual void loadFromByteArray(const unsigned char * data); // load this object using the byte array. virtual void storeToByteArray(unsigned char ** data, uint32_t& length) ; // store this object in the byte array. };

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值