如何使用Roslyn在给定的名称空间上下文中获得任意类型的最充分简化的类型名称?

时间:2020-05-21 23:20:20

标签: c# roslyn roslyn-code-analysis

我正在编写一个函数,该函数采用任何具体的或构造的Type,例如typeof(ValueTuple<Nullable<System.Int32>, double, List<string>),并返回一个字符串,该字符串是该类型的简化C#语法表示形式(即,(int?, double, List<string>)这个例子)。

这是我到目前为止所拥有的:

public static string ToCSharpString(this Type type, string[] usingNamespaces = null, Assembly[] usingAssemblies = null)
{
    var compilationUnit = SyntaxFactory.CompilationUnit();
    if (usingNamespaces != null)
    {
        compilationUnit = compilationUnit.AddUsings(
            Array.ConvertAll(usingNamespaces, n => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(n))));
    }
    else
    {
        compilationUnit = compilationUnit.AddUsings(
            SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")));
    }

    MetadataReference[] metadataReferences;
    if (usingAssemblies != null)
    {
        metadataReferences = Array.ConvertAll(usingAssemblies, u => MetadataReference.CreateFromFile(u.Location));
    }
    else
    {
        metadataReferences = new[]
        {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            MetadataReference.CreateFromFile(type.Assembly.Location)
        };
    }

    TypeSyntax typeName;
    using (var provider = new CSharpCodeProvider())
    {
        typeName = SyntaxFactory.ParseTypeName(provider.GetTypeOutput(new CodeTypeReference(type)));
    }

    var field = SyntaxFactory.FieldDeclaration(
        SyntaxFactory.VariableDeclaration(typeName).WithVariables(
            SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(
                SyntaxFactory.VariableDeclarator(
                    SyntaxFactory.Identifier("field")))));
    compilationUnit = compilationUnit.AddMembers(
        SyntaxFactory.ClassDeclaration("MyClass").AddMembers(
            field))
        .NormalizeWhitespace();

    var tree = compilationUnit.SyntaxTree;
    var compilation = CSharpCompilation.Create("MyAssembly", new[] { tree }, metadataReferences);
    var semanticModel = compilation.GetSemanticModel(tree);
    var root = tree.GetRoot();

    var typeSymbol = semanticModel.GetDeclaredSymbol(compilationUnit
        .DescendantNodes().OfType<ClassDeclarationSyntax>().Single()
        .Members.OfType<FieldDeclarationSyntax>().Single()
        .Declaration.Type);

    return typeSymbol.ToDisplayString(new SymbolDisplayFormat(
        typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
        miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes));
}

我正在尝试将几种已知的用于转换类型的方法组合在一起。

  • 类型->全限定名
    • 通过CodeDOM的CSharpCodeProvider.GetTypeOutput
  • 完全限定名称-> TypeSyntax
    • 通过Rosly的SyntaxFactory.ParseTypeName

现在,我想将.ToDisplayString()与几个不同的选项一起使用,但找不到无法从语义模型返回null的类型节点。

如何使用SymbolDisplayFormat格式化TypeSyntax?

此外,我希望此 会更改System.Int32-> int,但是,它不会自动修复Nullable<T>或{{ 1}}

如何执行适当的代码分析规则来替换这些类型名称?

1 个答案:

答案 0 :(得分:2)

文档状态GetDeclaredSymbol仅适用于

从MemberDeclarationSyntax,TypeDeclarationSyntax,EnumDeclarationSyntax,NamespaceDeclarationSyntax,ParameterSyntax,TypeParameterSyntax或UsingDirectiveSyntax的别名部分派生的任何类型

您似乎是QualifiedNameSyntax,这似乎与预期的输入很相符,但对Roslyn显然意味着其他的东西(我承认我没有理会它是否实际上从预期的类型之一继承)

但是,改为使用TypeInfo似乎可以使您的特定示例正常工作:

    var typeSymbol = semanticModel.GetTypeInfo(compilationUnit // just changed this method
        .DescendantNodes().OfType<ClassDeclarationSyntax>().Single()
        .Members.OfType<FieldDeclarationSyntax>().Single()
        .Declaration.Type); 
    return typeSymbol.Type.ToDisplayString(new SymbolDisplayFormat(
        typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
        miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); // I'm getting "(int?, double, List)" here