"Eval()"在C#中:将字符串转换为公式 [英] "Eval()" in C#: Converting a string into a formula
问题描述
我有一个包含数千个变量的程序.我需要对涉及其他变量的每个变量执行复杂的操作.
我将使用的某些公式将调用我定义的方法.因此,z的字符串可能是"x + y",但也可能是"NewMethod(x,y)"
我想做的是创建一个两列电子表格,其中包含每个变量名称和用于计算该变量值的公式(存储为字符串).对于C#程序中的每个变量,我将查找包含公式的字符串,然后计算该公式.
简单示例:
假设存在三个变量:x,y和z.
x = 10
y = 20
我查找z的公式,它返回以下字符串:
字符串="x + y"
我正在寻找一个功能等同于以下功能的产品:
z = eval(字符串)
这样z等于30.
如何在C#中执行此操作?
在此先感谢您的帮助.
I have a programs with thousands of variables. I need to perform complex operations on each of these variables that involves other variables.
Some of the formulas that I will using will call methods that I have defined. So the string for z may be "x + y", but it might also be "NewMethod(x,y)"
What I would like to do is create a two column spreadsheet containing each of the variable names and the formula (stored as a string) used to calculate that variable''s value. For each variable in the C# program, I would look up the string containing the formula and then calculate that formula.
Simple example:
Let''s assume that there are three variables: x, y, and z.
x = 10
y = 20
I look up the formula for z and it returns the following string:
string = "x + y"
I am looking for a function that would do the equivalent of:
z = eval(string)
such that z would equal 30.
How can I do this in C#?
Many thanks in advance for any help.
推荐答案
操作符重载对 ^ ]?
据我所知,在c#中没有等效项eval(如vb6).但是您可以使用system.CodeDom.Compiler命名空间来创建自己的eval函数.通过使用它,您可以即时编译代码并在程序中使用它.
Hi,
As I know there is no equivalent for eval (like vb6) in c#. but you can use system.CodeDom.Compiler namespace to create your own eval function. by using that you can compile your code on the fly and use it in your program.
感谢您的答复.在这种情况下,不确定操作符重载是否会有所帮助.如果我想对新的类对象执行标准操作,那将是很好的.
就我而言,我想做的是以下操作:
假设我们有一个带有以下变量的程序:
Thanks for your response. Not sure that operator overloading would help in this case. That would be good if I wanted to perform standard operations on a new class object.
In my case, what I want to do is the following:
Let''s assume that we have a program with the following variables:
double x1 = 20;<br />
double x2 = 30;<br />
double y = 100;<br />
string s = "y + NewMethod(x1, x2)";
此外,我们假设NewMethod()是对两个参数执行计算并返回double类型值的某种方法.例如,假设NewMethod(20,30)结果将产生610.23.
我正在寻找一种方法(出于演示目的,我们将其称为"Formula()"),例如:
z = Formula(s);
会产生与以下结果相同的结果:
z = y + NewMethod(x1, x2);
(即z等于710.23)
Furthermore, let''s assume that NewMethod() is some method that performs a calculation on its two parameters and returns a value of type double. For example, let''s assume that NewMethod(20,30) would produce 610.23 as a result.
I am looking for a method (let''s call it "Formula()" for demonstation purposes), such that:
z = Formula(s);
would produce the same result as:
z = y + NewMethod(x1, x2);
(i.e. z would be equal to 710.23)
这篇关于"Eval()"在C#中:将字符串转换为公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!