使用過Javascript中的Eval函數的兄弟肯定對這個函數情有獨鐘,該函數能動態的執行我們傳遞進去的表 達式。使用Eval函數咱們能輕松的制作可編程的程序,那C#是否也有這樣的函數呢?答案是肯定的,不過C#並 沒有實現現成的方法供我們使用。但是這並不能阻止咱們這幫愛偷懶的程序員們。
現在我們就在C#中 實現一個Eval函數吧,具體操作如下:

圖1

圖2

圖3

圖4
程序代碼
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
namespace CSHARP_EVAL_FUNCTION
{
public class EVAL
{
private static string prefix = @"using System;
public static class DynamicClass
{
public static void Bomb()
{";
public static string postfix = @"}}";
public string content { get; set; }
public void Eval()
{
if (content == "")
{
Console.WriteLine("必須為Content屬性賦予值");
return;
}
string code = prefix + content + postfix;
CompilerResults result = null;
using (var provider = new CSharpCodeProvider())
{
var options = new CompilerParameters();
options.GenerateInMemory = true;
result = provider.CompileAssemblyFromSource(options, code);
if (result.Errors.HasErrors)//編譯有錯誤
{
var errorMsg = new StringBuilder();
foreach (CompilerError error in result.Errors)
{
errorMsg.AppendFormat("Line:{0},Column:{1},Content:{2}", error.Line,
error.Column, error.ErrorText);
}
Console.WriteLine(errorMsg.ToString());
}
else//運行類 DynamicClass 中的HelloWorld方法
{
Type dynamicClass = result.CompiledAssembly.GetType("DynamicClass");
dynamicClass.InvokeMember("Bomb", BindingFlags.InvokeMethod |
BindingFlags.Static | BindingFlags.Public, null, null, null);
}
}
}
}
}
源碼下載:http://download.csdn.net/detail/ghostbear/4478128