我希望您能为我提供一种方法,以从C#脚本生成表达式树。目前,我正在使用IronPython,但如果可以更轻松地获取表达式树,我也可以考虑切换其他脚本语言。另外,我意识到如果可能的话,我可以通过实现自己的脚本语言来获得这个功能;然而,我更愿意使用已经创建好的脚本语言。
如果除了IronPython之外的脚本语言被推荐,我需要它具有以下功能:if语句(最好带有and/or),数学运算(+,-,*,/,log,%,^),循环和添加自定义函数的能力。
作为我尝试做的一个示例,我包含了两个代码块。其中一个使用创建并编译的表达式树计算奖金:
另一种方法使用IronPython计算奖金:
有没有办法使用IronPython(或任何其他脚本语言)从代码块中获取相同的表达式树?
如果除了IronPython之外的脚本语言被推荐,我需要它具有以下功能:if语句(最好带有and/or),数学运算(+,-,*,/,log,%,^),循环和添加自定义函数的能力。
作为我尝试做的一个示例,我包含了两个代码块。其中一个使用创建并编译的表达式树计算奖金:
using System;
using System.Linq.Expressions;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee() { Salary = 100000, BonusPct = .05 };
Expression<Func<Employee, double>> calcbonusExp = x => x.Salary * x.BonusPct; ;
var calcBonus = calcbonusExp.Compile();
Console.WriteLine(calcBonus(employee));
Console.WriteLine(calcbonusExp.NodeType);
Console.WriteLine(calcbonusExp.Body);
Console.WriteLine(calcbonusExp.Body.NodeType);
foreach (var param in calcbonusExp.Parameters)
{
Console.WriteLine(param.Name);
}
Console.Read();
}
}
public class Employee
{
public double Salary { get; set; }
public double BonusPct { get; set; }
}
}
另一种方法使用IronPython计算奖金:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee() { Salary = 100000, BonusPct = .05 };
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
ScriptSource source = engine.Execute(
@"def calcBonus(employee):
return employee.Salary * employee.BonusPct
", scope);
var calcAdd = scope.GetVariable("calcBonus");
var result = calcAdd(employee);
Console.WriteLine(result);
Console.Read();
}
}
public class Employee
{
public double Salary { get; set; }
public double BonusPct { get; set; }
}
}
有没有办法使用IronPython(或任何其他脚本语言)从代码块中获取相同的表达式树?