Dynamically execute string as code in C#

有些话、适合烂在心里 提交于 2019-12-08 12:08:34

问题


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

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


回答1:


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


来源:https://stackoverflow.com/questions/42992476/dynamically-execute-string-as-code-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!