在 C# 中动态执行字符串作为代码 [英] Dynamically execute string as code in C#

查看:80
本文介绍了在 C# 中动态执行字符串作为代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串转换为可执行代码.stringforeach 语句中.

I need to convert string to executable code. The string is in foreach statement.

foreach (InsuredItem _i in p.InsuredItems)
{
    string formula = "(_i.PremiumRate/100)*SumAssured";
    _i.Premium = (Execute formula);
}

公式是从设置加载的.这只是一个示范.我需要在 foreach 循环中执行字符串.谢谢.

The formula is loaded from setup. this is just a demonstration. I need to execute the string in foreach loop. Thanks.

推荐答案

假设您的公式是有效的 C# 代码并且它使用一组已知的局部变量(以便您可以创建一个包含所有这些的全局"类型),您应该可以使用 Roslyn 脚本 API 来执行此操作:

Assuming that your formula is valid C# code and that it uses a known set of local variables (so that you can create a "globals" type containing all of them), you should be able to use Roslyn scripting API to do this:

public class Globals
{
    public InsuredItem _i;
    public decimal SumAssured;
}

…

string formula = "(_i.PremiumRate/100)*SumAssured";
var script = CSharpScript.Create<decimal>(formula, globalsType: typeof(Globals))
    .CreateDelegate();

foreach (InsuredItem _i in p.InsuredItems)
{
    _i.Premium = await script(new Globals { _i = _i, SumAssured = SumAssured });
}

这篇关于在 C# 中动态执行字符串作为代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆