在VB中使用Roslyn,我正在尝试访问ITypeSymbol以获取使用类型推断声明的变量,但我正在努力返回正确的节点。我希望ITypeSymbol能够识别变量是否是引用类型。相比之下,这在C#中相对容易。在这种情况下,我们可以简单地使用node.Declaration.Type
但不能从VB声明器中获取。
在下面的示例中,我能够从AsClause
b
声明访问TypeSymbol,但对于a
变量中使用的推断类型,它是null:
Imports System.IO
Module Module1
Sub Main()
Dim code = "
Class C
Shared Sub Main()
Dim a = """"
Dim b As String = """"
End Sub
End Class"
Dim tree = SyntaxFactory.ParseSyntaxTree(code)
Dim compilation = VisualBasicCompilation.Create("test", {tree}, {MetadataReference.CreateFromAssembly(GetType(Object).Assembly)})
Dim result = compilation.Emit(New MemoryStream)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim localNodes = tree.GetRoot().DescendantNodes.OfType(Of LocalDeclarationStatementSyntax)
For Each node In localNodes
Dim localSym = semanticModel.GetDeclaredSymbol(node.Declarators.Single.Names.Single)
Trace.WriteLine(localSym.ToDisplayString())
' TODO: Figure how to get the typeinfo from inferred type
Dim symbol = semanticModel.GetTypeInfo(node) ' Is Nothing
Dim variableType = node.Declarators.First.AsClause?.Type ' This is null for inferred types
If variableType IsNot Nothing Then
Dim typeSymbol = SemanticModel.GetTypeInfo(variableType).ConvertedType
If typeSymbol.IsReferenceType AndAlso typeSymbol.SpecialType <> SpecialType.System_String Then
' Real processing goes here
End If
End If
Next
End Sub
End Module
答案 0 :(得分:3)
您可以从上面localSym
获取本地的类型:
DirectCast(localSym, ILocalSymbol).Type
遗憾的是,GetDeclaredSymbol()
的返回类型的重载不能更强类型,但不幸的是ModifiedIdentifierSyntax
无法知道是否来自本地字段等等。