我正在尝试在运行时编译此代码。但我收到编译错误。 如果我将生成的代码复制粘贴到Visual Studio,则编译没有问题。
using System;
using System.Collections.Generic;
namespace Evaluator
{
public static class Evaluator
{
public static bool Run()
{
int number = 100;
var hashSet = new HashSet<int> { 909, 910, 911, 912 };
if (hashSet.Contains(number)) return true;
// Code simplified
return false;
}
}
}
以下是我编译的方式
var parms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true,
IncludeDebugInformation = false
};
// parms.ReferencedAssemblies.Add()
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
var assembly = compiler.CompileAssemblyFromSource(parms, str).CompiledAssembly;
如果我将HashSet
更改为Dictionary
,则会正常编译。
答案 0 :(得分:1)
您必须为某些程序集添加一些引用:
GET /img/tap-logo.png HTTP/1.1
Host: tap.#######.com/
Connection: keep-alive
Pragma: no-cache
Cache-Control: max-age=0
Accept: image/webp,*/*;q=0.8
If-Modified-Since: Tue, 16 Jun 2015 12:23:44 GMT
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Referer: http://www.#######.com/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,en-GB;q=0.6
有趣的是,如果我编译并输出一个dll,而不是在内存中编译,如:
// Add these two lines
parms.ReferencedAssemblies.Add("System.dll");
parms.ReferencedAssemblies.Add("System.Core.dll");
// This line is yours
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
我不需要添加对parms.GenerateInMemory = false;
parms.OutputAssembly = "OutputAssembly.dll";
的引用。乐趣: - )