//编译器 ,见http://blog.csdn.net/wingfay/archive/2007/06/08/1643611.aspx  
private void Compiler(string code) 
        { 
            CompilerParameters vCompilerParameters = new CompilerParameters(); 
            vCompilerParameters.GenerateExecutable = false; 
            vCompilerParameters.GenerateInMemory = true; 
            vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); 
            string vSource = 
                "using System.Windows.Forms; " + 
                "public class Temp " + 
                "{ " + 
                "    public void Test() " + 
                "    { " + 
                "         " + code + " " + 
                "    } " + 
                "} "; 
            CompilerResults vCompilerResults = 
                CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource);             Assembly vAssembly = vCompilerResults.CompiledAssembly; 
            object vTemp = vAssembly.CreateInstance("Temp"); 
            MethodInfo vTest = vTemp.GetType().GetMethod("Test"); 
            vTest.Invoke(vTemp, null); 
        } //调用
string code = "         decimal value=80;decimal basicvalue=30;decimal score=0;if ((value / basicvalue) >= (105/100)) { score = 15; } else if (value / basicvalue >= 1 && value / basicvalue  < (105/100)) { score = 10; } else if (value / basicvalue  < 1) { score = 5; }      MessageBox.Show(score.ToString());     " 
Compiler(code);  
//score=?? 怎么在Compiler后面得到score的返回值? 

解决方案 »

  1.   

    调用上:string code = " decimal value=80;decimal basicvalue=30;decimal score=0;if ((value / basicvalue) >= (105/100)) { score = 15; } else if (value / basicvalue >= 1 && value / basicvalue   < (105/100)) { score = 10; } else if (value / basicvalue   < 1) { score = 5; }      return score;    "; 
    Compiler(code); 代码上改后如下:        private void Compiler(string code)
            {
                CompilerParameters vCompilerParameters = new CompilerParameters();
                vCompilerParameters.GenerateExecutable = false;
                vCompilerParameters.GenerateInMemory = true;
                vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                string vSource =
                    "using System.Windows.Forms; " +
                    "public class Temp " +
                    "{ " +
                    "    public decimal Test() " +
                    "    { " +
                    "         " + code + " " +
                    "    } " +
                    "} ";
                CompilerResults vCompilerResults =
                    CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource);            Assembly vAssembly = vCompilerResults.CompiledAssembly;
                object vTemp = vAssembly.CreateInstance("Temp");
                MethodInfo vTest = vTemp.GetType().GetMethod("Test");
                object obj = vTest.Invoke(vTemp, null);
            }