c语言eval函数,百行代码轻便实现C#中的Eval函数

百行代码轻松实现C#中的Eval函数

使用过Javascript中的Eval函数的兄弟肯定对这个函数情有独钟,该函数能动态的执行我们传递进去的表达式。使用Eval函数咱们能轻松的制作可编程的程序,那C#是否也有这样的函数呢?答案是肯定的,不过C#并没有实现现成的方法供我们使用。但是这并不能阻止咱们这帮爱偷懒的程序员们。

现在我们就在C#中实现一个Eval函数吧,具体操作如下:

152100686.jpg

图1

152100687.jpg

图2

152100688.jpg

图3

152100689.jpg

图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);

}

}

}

}

}

源码下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值