c# - 从字符串公式映射变量

标签 c# asp.net

<分区>

我有一个文本区域,用户可以在其中使用下拉列表(用于运算符、变量等)创建动态公式,如下所示:

basic / workingDays * attendingDays

basicworkingDaysattendingDays 的值保存在数据库中。我想在运行时从数据库映射这些变量。我该怎么做。

最佳答案

NCalc是一个非常强大的框架,您可以尝试一下。它们允许您定义听起来正是您所需要的动态参数。你可以这样做:

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

还有一些相关问题,例如 this onethis one提供一些其他选项。

关于c# - 从字符串公式映射变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495790/

相关文章:

asp.net - 如何将泛型类注册为 IHttpModule

asp.net - 如何在 ASP.NET GridView 中获取选中的项目

c# - 如何在 VB.Net/C# 和 ASP.NET 中的下拉列表中显示对象属性

c# - 在 C# 中,是否可以将两个不同的类作为返回类型从一层传递到另一层?

c# - .NET Standard 2.0 中的 Microsoft.AspNet.Identity 和 Microsoft.AspNet.Identity.EntityFramework

C# 释放 IntPtr 引用的内存

asp.net - Microsoft/Facebook 身份验证的高级功能在 Asp .Net Core RC1 上不可用

c# - midiInGetDevCaps Midi 设备名称

c# - LINQ 查询除了不起作用,List<long?> 与 List<long>

Asp.net 必填字段验证器问题