English 中文(简体)
将插图改为变名称[复制]
原标题:Converting string to variable name [duplicate]
  • 时间:2012-01-12 07:01:50
  •  标签:
  • c#
  • asp.net

我有以下声明:

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);
    }
}
问题回答

是的。 最简单的方法是计算。 Repalce(“价值1”,价值1.ToString())。 替换(“价值2”,价值2.ToString()),然后说,虽然最复杂的是全方位描述的语言。 如果你想操纵同样的扼杀性多倍,可以使用强食。

::EDIT:: This question has been asked before. Take a look at the comments.

你们的法典中有一些不正确的说法。

解决办法是:

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

这是因为,如果你在报价中贴出价值1和价值2,他们就掌握了任何内容,而成为字面。 你们需要他们的价值观。 因此,他们改道,然后做第三行,或你想要做什么。

也许你应该用字典来这样做。

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签