问题描述
我的代码是这样的:
public static bool CompileClient(out string[] errors)
{
using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"))
{
CompilerParameters cp = new CompilerParameters
{
GenerateExecutable = true,OutputAssembly = $"./hi.exe",CompilerOptions = "/optimize",TreatWarningsAsErrors = false
};
if (provider.Supports(GeneratorSupport.EntryPointMethod))
cp.MainClass = "Namespace.Program";
CompilerResults cr = provider.CompileAssemblyFromFile(cp,Directory.GetFiles("./Sourcecode/")); // Invoke compilation
if (cr.Errors.Count > 0)
{
List<string> _errors = new List<string>();
for (int i = 0; i < cr.Errors.Count; i++)
_errors.Add(cr.Errors[i].ToString());
errors = _errors.ToArray();
return false;
}
else
{
errors = null;
return true;
}
}
}
/Sourcecode/ 中的 .cs 文件包含以下代码:
$"Hello {name}"
编译文件时出现此错误:error CS1056: Unexpected character '$'.
有没有办法在不使用 string + string 或 string.Format() 的情况下修复错误? 也许更改版本或其他什么..?
解决方法
“字符串插值”的 $ 表示法(基本上是 string.Format() 的简写)是在 c# 版本 6 中引入的,因此您需要一个至少支持该版本的编译器。
这个答案可能有帮助:
Which C# compiler version to compile C# 7.3 with the CSharpCodeProvider class?