从 Roslyn ClassDeclarationSyntax 获取类全名(包括命名空间) [英] Getting Class FullName (including namespace) from Roslyn ClassDeclarationSyntax

查看:84
本文介绍了从 Roslyn ClassDeclarationSyntax 获取类全名(包括命名空间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 roslyn 语法树的 ClassDeclarationSyntax.我是这样读的:

I've a ClassDeclarationSyntax from a syntax tree in roslyn. I read it like this:

var tree = SyntaxTree.ParseText(sourceCode);
var root = (CompilationUnitSyntax)tree.GetRoot();

var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>();

标识符只包含类名而没有命名空间的信息,所以缺少fullType Name.像MyClass"但没有Namespace1.MyClass"

The identifier only contains the name of the class but no information about the namespace, so the fullType Name is missing. Like "MyClass" but noch "Namespace1.MyClass"

获取语法的命名空间/FulltypeName 的推荐方法是什么?

what is the recommended way to get the namespace / FulltypeName of the Syntax?

推荐答案

你可以使用我写的辅助类来做到这一点:

you can do this using the helper class I wrote:

NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;
if (!SyntaxNodeHelper.TryGetParentSyntax(classDeclarationSyntax, out namespaceDeclarationSyntax))
{
    return; // or whatever you want to do in this scenario
}

var namespaceName = namespaceDeclarationSyntax.Name.ToString();
var fullClassName = namespaceName + "." + classDeclarationSyntax.Identifier.ToString();

和助手:

static class SyntaxNodeHelper
{
    public static bool TryGetParentSyntax<T>(SyntaxNode syntaxNode, out T result) 
        where T : SyntaxNode
    {
        // set defaults
        result = null;

        if (syntaxNode == null)
        {
            return false;
        }

        try
        {
            syntaxNode = syntaxNode.Parent;

            if (syntaxNode == null)
            {
                return false;
            }

            if (syntaxNode.GetType() == typeof (T))
            {
                result = syntaxNode as T;
                return true;
            }

            return TryGetParentSyntax<T>(syntaxNode, out result);
        }
        catch
        {
            return false;
        }
    }
}

这里没有什么过于复杂的事情......命名空间在语法树的上"是有道理的(因为类包含在命名空间中)所以你只需要向上"移动语法树直到找到命名空间并将其附加到 ClassDeclarationSyntax 的标识符.

There is nothing overly complex going on here... it makes sense that the namespace would be "up" the syntax tree (because the class is contained within the namespace) so you simply need to travel "up" the syntax tree until you find the namespace and append that to the identifier of the ClassDeclarationSyntax.

这篇关于从 Roslyn ClassDeclarationSyntax 获取类全名(包括命名空间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆