正在将字符串转换为变量名

本文关键字:变量名 转换 字符串 | 更新日期: 2023-09-27 18:20:08

我有以下声明:

int value1 =5 , value2 =10 ,value3;     
string calculate ="value1 + value2"; // dynamic string

我需要执行

value3 = convert.To int32(calculate );

有没有可能计算动态变量赋值。。。

正在将字符串转换为变量名

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

确实如此。最简单的方法就是简单地计算。重新定位("value1",value1.ToString())。替换("value2",value2.ToString(。如果您想多次操作同一个字符串,可以使用StringBuilder。

::编辑::这个问题以前有人问过。看看评论。

您的代码中有几个不正确的语句。

解决方案是:

int value1 =5 , value2 =10 ,value3;     
string calculate =value1.ToString() + value2.ToString(); // dynamic string
value3 = Convert.ToInt32(calculate );

这是因为当你把value1和value2放在引号里时,它们不会有任何内容,而是变成了文字。而你需要他们的价值观。因此,将它们转换为字符串,然后执行第三行或您想对它们执行的任何其他操作。

也许你应该用dictionary。。。像这个

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