繁体   English   中英

Roslyn-编译简单的类:“找不到类型或名称空间名称'string'…”

[英]Roslyn - compiling simple class: “The type or namespace name 'string' could not be found…”

我正在使用Roslyn API生成和编译一个类。 生成的类如下所示:

namespace MyCompany.Product
{
    public class TestClass
    {
        public void Configure(string id)
        {
        }
    }
}

但是,当我编译它时,Emit(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)
            {
            } 
        }
    }

但是,如果我编译下面的类,但使用类型为'string'的常量,则会按预期进行编译,因此在声明为方法参数类型时,它不喜欢'string':

namespace MyCompany.Product
{
    public class TestClass
    {
        public const string Id = "e1a64bdc-936d-47d9-aa10-e8634cdd7070";
    }
}

我正在使用框架4.6.1,Microsoft.CodeAnalysis版本= 1..3.1.0

我喂你的第一个示例代码插入CSharpSyntaxTree.ParseText ,结果到Compile -它如预期成功编译。

我的猜测是您正在编译的节点类型某种程度上是错误的。 string是别名为System.String类型的C#关键字,本身不是类型名称。

您可以使用Roslyn语法可视化器检查您自己的SyntaxTreeCSharpSyntaxTree.ParseText从预期输出生成的CSharpSyntaxTree.ParseText之间的差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM