CodeDOM 簡易使用方法

CodeDOM 簡易使用方法

數十年前, 曾用 Delphi 來開發 "VB 程式語言教導", 可以馬上執行 VB 程式碼的結果,
當時也花了一個多月來開發, 如今小小地用這個 CodeDOM 的技術, 花不到一小時... @@"
範例如下:

public delegate void IncDelegate(ref int cnt);
private void TestCodeDom()
{
	int cnt = 0;
	string testcode = @"
		using System.Windows.Forms;
		public class clsInc
		{
			public void inc(ref int cnt)
			{
				cnt++;
				//MessageBox.Show(""in clsInc"");
			}

			public static void sinc(ref int cnt)
			{
				cnt += 3;
			}
		}";
	Assembly assembly = CompileSource(testcode);
	if (assembly != null)
	{
		Type clsIncype = assembly.GetType("clsInc");

		MethodInfo incMethod = clsIncype.GetMethod("inc", BindingFlags.Public | BindingFlags.Instance);
		IncDelegate incInc = (IncDelegate)Delegate.CreateDelegate(typeof(IncDelegate), null, incMethod);
		incInc(ref cnt);
		//btnStart.Text = cnt.ToString();

		MethodInfo sincMethod = clsIncype.GetMethod("sinc", BindingFlags.Public | BindingFlags.Static);
		IncDelegate sincInc = (IncDelegate)Delegate.CreateDelegate(typeof(IncDelegate), null, sincMethod);
		sincInc(ref cnt);
		btnStart.Text = cnt.ToString();

	}
}

private Assembly CompileSource(string sourceCode)
{
	Assembly ret = null;
	try
	{
		CodeDomProvider cpd = new CSharpCodeProvider();
		CompilerParameters cp = new CompilerParameters();
		cp.ReferencedAssemblies.Add("System.dll");
		cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
		cp.GenerateExecutable = false;

		CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

		if (cr.Errors.Count > 0)
		{
			string errmsg = "";
			foreach (CompilerError CompErr in cr.Errors)
			{
				errmsg = errmsg +
					String.Format("Error Number:{0}\r Line number:{1},{2}\r {3}",
						CompErr.ErrorNumber,
						CompErr.Line,
						CompErr.Column,
						CompErr.ErrorText + Environment.NewLine + Environment.NewLine);
			}
			MessageBox.Show(errmsg);
		}
		else
		ret = cr.CompiledAssembly;
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}
	return ret;
}

目前仍然摸索中~ 留個資料, 方便日後查詢