且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#中动态评估表达式

更新时间:2023-02-18 08:52:49

1)我建议你改变你的方法用户。此设计不可扩展。你可以做的是,有一个表 UserId,Component and Formula 。通过这样做,您可以根据用户ID筛选出数据,并获取单个用户的组件和公式。



1) I would suggest you to change your approach of having one table per user. This design is not scaleable. What you can do is, have one table with columns UserId, Component and Formula. By doing this you can filter out data based on user ids and get the component and Formula for an individual user.

UserId Component Formula
1  	    CA        800Rs
1  	    IN        50%Rest
1  	    Basic	  40%Total
1  	    HRA       40%Basic
1  	    SA	      50%Rest
2  	    CA        900Rs
2  	    IN        10%Rest
2  	    Basic	  30%Total
2  	    HRA	      20%Basic
2  	    SA	      20%Rest





2 )可以动态评估您的表达式。检查以下链接:

.Net Expression Evaluator using DynamicMethod [ ^ ]

评估C#代码(评估函数) [ ^ ]

您需要从数据库中获取公式,然后将它们提供给您的自定义评估程序,如上面的链接所述。



2) It is possible to dynamically evaluate your expressions. check the links below:
.Net Expression Evaluator using DynamicMethod[^]
Evaluate C# Code (Eval Function)[^]
You need to fetch the formulas from database and then feed them to your custom evaluator as described in links above.


string Rest = "";
                for (int j = 0; j < dsAllFarmula.Tables[0].Rows.Count; j++)
                {
                   Component cmp = new Component();
                    cmp.ComponentName=dsAllFarmula.Tables[0].Rows[j]["SalaryComponent"].ToString();
                    cmp.CmponentValue = dsAllFarmula.Tables[0].Rows[j]["Farmula"].ToString();
                    Structure.Add(cmp);
                    if (!cmp.CmponentValue.Contains("Rest"))
                        Rest += "("+cmp.ComponentName+")+";
                   // double val= _model.Evaluate(cmp.CmponentValue);
                }
                Rest = Rest.Remove(Rest.Length-1);
                Rest = "Total-(" + Rest+")";
                foreach (var lom in Structure)
                {
                    Rest = Rest.Replace(lom.ComponentName, lom.CmponentValue);
                }

                foreach (var item in Structure)
                {
                    item.CmponentValue = item.CmponentValue.Replace("Rest", Rest);
                    foreach (var pre in Structure)
                        item.CmponentValue = item.CmponentValue.Replace(pre.ComponentName, pre.CmponentValue);

                }