我们可以从Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax中获取Syste

本文关键字:TypeSyntax Syntax 获取 Syste CSharp CodeAnalysis Microsoft 我们 | 更新日期: 2023-09-27 18:19:46

我们可以从Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax中获得System.Type或基本上完全限定的类型名称吗?问题是,TypeSyntax返回类型的名称,因为它是在可能不是完全限定类名的代码中编写的,我们无法从中找到type。

我们可以从Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax中获取Syste

要获得一段语法的完全限定名称,需要使用SemanticModel来访问其符号。我在博客上写了一篇语义模型指南:立即学习Roslyn:语义模型简介

根据您之前的问题,我假设您正在查看字段。

var tree = CSharpSyntaxTree.ParseText(@"
class MyClass
{
    int firstVariable, secondVariable;
    string thirdVariable;
}");
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { mscorlib });
//Get the semantic model
//You can also get it from Documents
var model = compilation.GetSemanticModel(tree);
var fields = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>();
var declarations = fields.Select(n => n.Declaration.Type);
foreach (var type in declarations)
{
    var typeSymbol = model.GetSymbolInfo(type).Symbol as INamedTypeSymbol;
    var fullName = typeSymbol.ToString();
    //Some types like int are special:
    var specialType = typeSymbol.SpecialType;
}

您还可以通过以下方式获得声明本身的符号(而不是声明上的类型):

var declaredVariables = fields.SelectMany(n => n.Declaration.Variables);
foreach (var variable in declaredVariables)
{
    var symbol = model.GetDeclaredSymbol(variable);
    var symbolFullName = symbol.ToString();
}

最后要注意的是:对这些符号调用.ToString()会得到它们的完全限定名称,但不会得到它们的全限定元数据名称。(嵌套类在类名和泛型以不同方式处理之前有+)。