using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp12
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){}private void button1_Click(object sender, EventArgs e){MessageBox.Show(GetCode2());}public static string GetCode2(){StringBuilder sb = new StringBuilder();sb.Append("using System;");sb.Append(Environment.NewLine);sb.Append("namespace DynamicCodeGenerate");sb.Append(Environment.NewLine);sb.Append("{");sb.Append(Environment.NewLine);sb.Append(" public class HelloWorld");sb.Append(Environment.NewLine);sb.Append(" {");sb.Append(Environment.NewLine);sb.Append(" public string OutPut()");sb.Append(Environment.NewLine);sb.Append(" {");sb.Append(Environment.NewLine);sb.Append(" return \"Hello world!\";");sb.Append(Environment.NewLine);sb.Append(" }");sb.Append(Environment.NewLine);sb.Append(" }");sb.Append(Environment.NewLine);sb.Append("}");string code = sb.ToString();return code;}}
}
點擊按鈕運行后結果如下:
然后我把它的輸出類型改為類庫:
然后去新建第二個窗體應用,然后引用上面的項目
代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp12;namespace WindowsFormsApp1
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){//WindowsFormsApp12.Form1 f1 = new WindowsFormsApp12.Form1();MessageBox.Show( WindowsFormsApp12.Form1.GetCode2());}}
}