我们可以从Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax获取System.Type吗?

问题描述:

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

+1

请注意,您无法轻松获取System.Type,但可以获取Microsoft.CodeAnalysis.ITypeSymbol。乔希的回答已经给出了一个很好的解释。请注意,在大多数情况下,System.Type实际上并不是您想要的,因为这意味着您的流程中会以不需要的方式加载类型。 –

要获得一段语法的全限定名称,您需要使用SemanticModel来获得对其符号的访问权限。我已经在我的博客上撰写了语义模型指南:Learn Roslyn Now: Introduction to the Semantic Model

根据您的previous question,我假设您正在查看字段。

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()给你他们的完全合格名称,但不包括其完全限定的元数据名称。 (嵌套类在之前,其类名和泛型处理方式不同)。

+1

为了获取元数据名称,我有一个方法[在这里](http://*.com/a/27106959/73070),据我所知,仍然没有公开访问的方法在Roslyn中获取。 – Joey

+0

我经常在我自己的代码中使用它:) – JoshVarty