HashSet的运行时编译<T>
Runtime compilation of HashSet<T>
我正在尝试在运行时编译这段代码。但我收到编译错误。
如果我将生成的代码复制粘贴到 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
,则编译没有问题。
您必须添加对某些程序集的引用:
// Add these two lines
parms.ReferencedAssemblies.Add("System.dll");
parms.ReferencedAssemblies.Add("System.Core.dll");
// This line is yours
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
有趣的是,如果我编译并输出一个dll,而不是在内存中编译,比如:
parms.GenerateInMemory = false;
parms.OutputAssembly = "OutputAssembly.dll";
我不需要添加对 System.dll
的引用。有趣:-)
我正在尝试在运行时编译这段代码。但我收到编译错误。 如果我将生成的代码复制粘贴到 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
,则编译没有问题。
您必须添加对某些程序集的引用:
// Add these two lines
parms.ReferencedAssemblies.Add("System.dll");
parms.ReferencedAssemblies.Add("System.Core.dll");
// This line is yours
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
有趣的是,如果我编译并输出一个dll,而不是在内存中编译,比如:
parms.GenerateInMemory = false;
parms.OutputAssembly = "OutputAssembly.dll";
我不需要添加对 System.dll
的引用。有趣:-)