简体   繁体   中英

Dynamically execute string as code in C#

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM