C# Roslyn-编译简单类:“简单类”;类型或命名空间名称';字符串';找不到……”;
我正在使用Roslyn API生成和编译一个类。生成的类如下所示:C# Roslyn-编译简单类:“简单类”;类型或命名空间名称';字符串';找不到……”;,c#,roslyn,C#,Roslyn,我正在使用Roslyn API生成和编译一个类。生成的类如下所示: namespace MyCompany.Product { public class TestClass { public void Configure(string id) { } } } 但是,当我编译它时,Emit(ted)结果给出: 错误CS0246:找不到类型或命名空间名称“string”(是否缺少using指令或程序集引用?) 以下是执行编译的
namespace MyCompany.Product
{
public class TestClass
{
public void Configure(string id)
{
}
}
}
但是,当我编译它时,Emit(ted)结果给出:
错误CS0246:找不到类型或命名空间名称“string”(是否缺少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)
{
}
}
}
我使用的是framework 4.6.1,Microsoft.CodeAnalysis版本=1.3.1.0我将您的第一个示例代码片段输入到
CSharpSyntaxTree.ParseText
中,并将结果输入到编译中
-它按预期成功编译
我的猜测是,您正在编译的节点类型在某种程度上是错误的string
是一个C#关键字,它为系统别名。string
类型本身不是类型名称
您可以使用Roslyn语法可视化工具检查您自己的
SyntaxTree
与预期输出中由CSharpSyntaxTree.ParseText
生成的语法树之间的差异。尝试使用AssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)添加到
todefaultCompilationOptions
@m0sa-仍然无法使用该选项谢谢。我按照您的建议检查了我的语法树,并将其与语法可视化工具进行了比较。果然,我注意到了一个不同。我使用的是.WithType(SyntaxFactory.IdentifierName(“字符串”)
而不是.WithType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)))
。现在,这项工作如预期的那样
namespace MyCompany.Product
{
public class TestClass
{
public const string Id = "e1a64bdc-936d-47d9-aa10-e8634cdd7070";
}
}