我有以下声明:
int value1 =5 , value2 =10 ,value3;
string calculate ="value1 + value2"; // dynamic string
我需要执行
value3 = convert.To int32(calculate );
是否有可能计算动态变量分配......
答案 0 :(得分:1)
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections.Generic;
static public class Sample {
static public double eval(string exp, Dictionary<string,string> varlist){
CSharpCodeProvider csCompiler = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
// compilerParameters.ReferencedAssemblies.Add("System.dll");
string temp =
@"static public class Eval {
static public double calc() {
double exp = $exp;
return exp;
}
}";
string equation = exp;
foreach(var key in varlist.Keys){
equation = equation.Replace(key, varlist[key]);
}
temp = temp.Replace("$exp", equation);
CompilerResults results = csCompiler.CompileAssemblyFromSource(compilerParameters,
new string[1] { temp });
if (results.Errors.Count == 0){
Assembly assembly = results.CompiledAssembly;
MethodInfo calc = assembly.GetType("Eval").GetMethod("calc");
double answer = (double)calc.Invoke(null, null);
return answer;
} else {
Console.WriteLine("expression errors!");
foreach(CompilerError err in results.Errors){
Console.WriteLine(err.ErrorText);
}
return Double.NaN;
}
}
}
class Program {
static void Main(){
double value3 = 3;
double value2 = 2;
double value8 = 8;
double value7 = 7;
double value6 = 6;
string calculate = " value3 / value2 * value8 / (36 * 840) * value7/ (2.2046 * value6) * value7";
var vars = new Dictionary<string,string>();
vars.Add("value3", value3.ToString("F"));
vars.Add("value2", value2.ToString("F"));
vars.Add("value8", value8.ToString("F"));
vars.Add("value7", value7.ToString("F"));
vars.Add("value6", value6.ToString("F"));
double result = Sample.eval(calculate, vars);
Console.WriteLine("{0:F8}", result);
}
}
答案 1 :(得分:0)
是的。最简单的方法就是计算.Repalce(“value1”,value1.ToString())。替换(“value2”,value2.ToString())然后解析它,而最复杂的是一个完整的脚本语言。如果要多次操作相同的字符串,可以使用StringBuilder。
:: EDIT :: 之前已经问过这个问题。看看评论。
答案 2 :(得分:0)
您的代码中有几个不正确的陈述。
解决方案是:
int value1 =5 , value2 =10 ,value3;
string calculate =value1.ToString() + value2.ToString(); // dynamic string
value3 = Convert.ToInt32(calculate );
这是因为当你将value1和value2放在引号内时,它们不会有任何内容,但会成为文字。而你需要他们的价值观。因此,将它们转换为字符串,然后执行第三行或其他任何您想要用它们做的事情。
答案 3 :(得分:0)
也许你应该用字典做这件事......就像这样
Dictionary<string, int> d = new Dictionary<string, int>();
d["value1"] = 5;
d["value2"] = 10;
string calculate = "value1 + value2";
string[] parts = string.Split(new[]{" + "}, StringSplitOptions.RemoveEmptyEntries);
int result = 0;
foreach(var part in parts)
{
result += d[part];
}
// Do something with result