gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:27:14 26 4
gpt4 key购买 nike

我们能否从 Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax 获取 System.Type 或本质上完全限定的类型名称?问题是,TypeSyntax 返回类型的名称,因为它是用代码编写的,可能不是完全合格的类名,我们无法从中找到 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() 会为您提供它们的完全限定名称,而不是它们的完全限定元数据名称。 (嵌套类在其类名和泛型之前有 +,处理方式不同)。

关于c# - 我们可以从 Microsoft.CodeAnalysis.CSharp.Syntax.TypeSyntax 获取 System.Type 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com