从字符串公式映射变量 [英] Mapping variables from a string formula
问题描述
我有一个textarea在这里用户可以创建使用下拉列表动态公式(运营商,变量等)是这样的:
I have a textarea where user can create a dynamic formulas using dropdown lists(for operators, variables etc) like this:
basic / workingDays * attendingDays
其中的值基本
, workingDays
, attendingDays
保存在数据库中。我想在运行时从数据库中的这些变量映射。我怎样才能做到这一点。
where values of basic
, workingDays
, attendingDays
are saved in database. I want to map these variable from database during runtime. How can I do this.
推荐答案
NCalc 是一个非常强大的框架,你可以试试。他们让你定义这听起来像正是你需要的动态参数。你可以做这样的事情:
NCalc is a very powerful framework that you could try. They let you define dynamic parameters which sounds like exactly what you need. You can do something like this:
var e = new Expression("basic / workingDays * attendingDays);
//Set up a custom delegate so NCalc will ask you for a parameter's value
// when it first comes across a variable
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "basic")
args.Result = GetBasicValueFromSomeWhere();
else if (/* etc. */)
{
//....
}
//Or if the names match up you might be able to something like:
args.Result = dataRow[name];
};
var result = e.Evaluate();
也有一些相关的问题在那里,如这个和<一个href=\"http://stackoverflow.com/questions/4384837/is-there-a-method-that-will-evaluate-a-string-and-produce-an-integer-assuming-th\">this 之一,让一些其他的选择。
There are also some related questions out there such as this one and this one that give some other options.
这篇关于从字符串公式映射变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!