解决方案 »
- Winform项目分辨率修改
- DropDownList选择后,GridView不显示数据
- 高难度问题: 怎样禁止双击treeview节点时自动展开或者折叠的行为
- "无法在证书存储区中找到清单签名证书" 什么意思?
- 小菜问个超简单问题
- 在用连接字符串连接本地数据库时,出现“未响应”,怎么回事?
- 求助:我有4个datagridview 需要导入到同一个excel文件里的不同sheets里
- 如何给XmlDocument对象添加一行?
- remoting的底层采用的是什么?socket吗?
- 大家帮忙看看我的SqlCommand.ExecuteNoQuery为什么总是返回-1?
- 求教 怎么样才能在bitmap上画带cleartype的文本
- C# 两表比对获取差异的算法
public static float GetInterest(int Q)
{
if (Q <= 40 || Q >= 450)
{
throw new ArgumentOutOfRangeException("Q is invalid");
}
float Y = 0.9F;
if (Q >= 100)
{
Y += 0.02F;
}
return Y;
}
public class CsharpStringEvalEngine
{
/// <summary>
/// C#表达式计算 注意区分大小写
/// </summary>
/// <param name="expression">普通的C#字符串表达式</param>
/// <returns></returns>
public object Eval(string expression)
{
string CLASSNAME = "Calc";
string METHODNAME = "Run"; //创建编译器实例。
CSharpCodeProvider complier = new CSharpCodeProvider(); //设置编译参数。
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true; //创建动态代码。
StringBuilder code = new StringBuilder();
code.Append("using System; \n");
code.Append("using System.Text; \n");
code.Append("using System.Text.RegularExpressions; \n");
code.Append("using System.Collections; \n");
code.Append("using System.Collections.Generic; \n");
code.Append("using System.Collections.Specialized; \n");
code.Append("using System.Data; \n");
code.Append("using System.Xml; \n");
code.Append("public class " + CLASSNAME + "\n");
code.Append("{\n");
code.Append(" public object " + METHODNAME + "()\n");
code.Append(" {\n");
code.Append(" return " + expression + ";\n");
code.Append(" }\n");
code.Append("}");
//编译代码。
CompilerResults cr = complier.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
{
StringBuilder error = new StringBuilder();
error.Append("Error Compiling Expression: "); foreach (CompilerError err in cr.Errors)
{
error.AppendFormat("{0}\n", err.ErrorText);
} throw new Exception("Error Compiling Expression: " + error.ToString());
}
else
{
//获取编译后的程序集。
Assembly assembly = cr.CompiledAssembly; //动态调用方法。
object eval = assembly.CreateInstance(CLASSNAME);
MethodInfo method = eval.GetType().GetMethod(METHODNAME);
return method.Invoke(eval, null);
}
}
}动态编译。以上以前写的代码仅供参考。
注意这些地方:
code.Append(" public object " + METHODNAME + "()\n");
code.Append(" {\n");
code.Append(" return " + expression + ";\n");
code.Append(" }\n");当然,还有其他办法,自己可以研究下。