我正在使用VS2010,只要我添加该行“DataTable table = null;”,这里发生的错误是代码:
public static object GetLambdaResult(string expression)
{
string className = "ExecuteLambda";
string methodName = "Run";
var providerDic = new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } };
ICodeCompiler complier = (new CSharpCodeProvider(providerDic).CreateCompiler());
CompilerParameters paras = new CompilerParameters();
paras.GenerateExecutable = false;
paras.GenerateInMemory = true;
paras.ReferencedAssemblies.Add("System.dll");
paras.ReferencedAssemblies.Add("System.Data.dll");
StringBuilder classSource = new StringBuilder();
classSource.Append("using System; \n");
classSource.Append("using System.Data; \n");
classSource.Append("namespace AutoRun \n");
classSource.Append("{\n");
classSource.AppendFormat(" public class {0} \n", className);
classSource.Append(" {\n");
classSource.AppendFormat(" public static object {0}()\n", methodName);
classSource.Append(" {\n");
classSource.Append(" DataTable table= null;\n");
classSource.AppendFormat(" return {0};\n", expression);
classSource.Append(" }\n");
classSource.Append(" }\n");
classSource.Append("}");
CompilerResults result = complier.CompileAssemblyFromSource(paras, classSource.ToString());
Assembly assembly = result.CompiledAssembly;
object eval = assembly.CreateInstance("AutoRun." + className);
MethodInfo method = eval.GetType().GetMethod(methodName);
object reobj = method.Invoke(eval, null);
GC.Collect();
return reobj;
}
我得到一个 FileNotFoundException,{“无法加载文件或程序集”文件:/// C:\\Users\\Administrator\\AppData\\Local\\Temp\\12azlzyr.dll“或其依赖项之一
. 系统找不到指定的文件。“:”文件:///C:\\Users\\Administrator\\AppData\\Local\\Temp\\12azlzyr.dll”
问题是 classSource.Append("DataTable table= null;\n"); 和
paras.ReferencedAssemblies.Add("System.Data.dll"); 我还不知道怎么解决
经过长时间的搜索,我找到了解决方案,需要添加xml引用paras.ReferencedAssemblies.Add("System.XML.dll");