我正在使用Roslyn API來生成和編譯類。生成的類看起來是這樣的:Roslyn - 編譯簡單類:「無法找到類型或名稱空間名稱字符串...」
namespace MyCompany.Product
{
public class TestClass
{
public void Configure(string id)
{
}
}
}
然而,當我來到編譯它,所述發送(TED)結果給出:
錯誤CS0246:類型或命名空間名稱「字符串」不能找到(是否缺少using指令或程序集引用?)
這裏是進行編譯的方法:
private static readonly IEnumerable<string> DefaultNamespaces = new[]
{
"System",
"System.IO",
"System.Net",
"System.Linq",
"System.Text",
"System.Text.RegularExpressions",
"System.Collections.Generic"
};
public void Compile(IEnumerable<SyntaxTree> syntaxes, string targetPath)
{
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
// assemblyPath = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
IEnumerable<MetadataReference> defaultReferences = new[]
{
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
};
CSharpCompilationOptions defaultCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release)
.WithUsings(DefaultNamespaces);
CSharpCompilation compilation = CSharpCompilation.Create(
targetPath,
syntaxTrees: syntaxes,
references: defaultReferences,
options: defaultCompilationOptions);
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
// here, result.Success = false, with it's Diagnostics collection containing the error
if (!result.Success)
{
}
}
}
但是,如果我編譯下面的類,但使用類型「字符串」的一個常數,它編譯如預期,因此方法參數類型聲明,當它不喜歡「串」:
namespace MyCompany.Product
{
public class TestClass
{
public const string Id = "e1a64bdc-936d-47d9-aa10-e8634cdd7070";
}
}
我正在使用框架4.6.1,Microsoft.CodeAnalysis版本= 1.3.1.0
嘗試添加到'.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)'到'defaultCompilationOptions'。 – m0sa
@ m0sa - 仍然無法使用該選項 – PhatBuck