【发布时间】:2017-06-16 23:36:48
【问题描述】:
我正在尝试在运行时编译代码并创建其中一个类的实例,但是在使用字符串插值等 c# 6+ 功能时出现一些错误。这是我用来编译的代码:
using (var cs = new CSharpCodeProvider())
{
var assembly = typeof(MyType).Assembly;
var cp = new CompilerParameters()
{
GenerateInMemory = false,
GenerateExecutable = false,
IncludeDebugInformation = true,
};
if (Environment.OSVersion.Platform.ToString() != "Unix") cp.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
else cp.TempFiles.KeepFiles = true;
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add(assembly.Location);
CompilerResults cr;
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
cr = cs.CompileAssemblyFromFile(cp, files);
}
else cr = cs.CompileAssemblyFromFile(cp, new string[] { path });
if (cr.Errors.HasErrors)
throw new Exception("Compliation failed, check your code.");
var types = cr.CompiledAssembly.GetTypes();
var myType = types.Where(x => x.GetInterfaces().Contains(typeof(MyType))).FirstOrDefault();
if (myType == null)
throw new TypeLoadException("Could not find MyType class");
return (MyType)cr.CompiledAssembly.CreateInstance(myType.FullName);
}
现在,如果我尝试编译使用以下代码的代码:
string name = $"My name is {name}";
我得到了这个例外:
Unexpected character '$'
【问题讨论】:
-
如何编译这段代码?使用哪个编译器版本?您需要一个能够理解并能够解析 C# 6.0 语法的编译器
-
您使用的是哪个 Visual Studio 版本?要获得完整的 C# 6.0 支持,您需要 VS2015 或 VS2017。
-
@Atesh052 我正在使用 VS2017。
-
@mjwills 我该如何检查?
-
那些看起来像正确的版本。 stackoverflow.com/a/40311406/34092 有帮助吗?
标签: c# compilation c#-6.0 runtime-compilation