如何获得罗斯林semanticmodel模块的祖先? [英] How to get module ancestor in roslyn semanticmodel?

查看:227
本文介绍了如何获得罗斯林semanticmodel模块的祖先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待得到一个模块的罗斯林semanticmodel祖先



在这样一个类:



<使用系统pre> 命名空间NAME1.NAME2
{
;
...

公共部分MyClass类:祖先<参数1,参数2>
{
}
}



所以我想获得祖先<参数1,参数2> (以及后来的参数1 参数2 )<​​/ p>

我使用这个代码来创建semanticmodel:

  SyntaxTree树= CSharpSyntaxTree.ParseFile(moduleAutoGenPath); 
CompilationUnitSyntax根=(CompilationUnitSyntax)tree.GetRoot();
变种NAMESPACE =((NamespaceDeclarationSyntax)(root.Members [0]))Name.ToString();
VAR编译= CSharpCompilation.Create(命名空间中,新[] {}树)AddReferences(新MetadataFileReference(typeof运算(对象).Assembly.Location))。



我期待在 compilation.Assembly.Modules 但没有找到祖先..



我是在好办法吗? ?或完全失去


解决方案

如果你想获得的基类,这样做:

  VAR classDeclaration = someNode.Ancestors()OfType< ClassDeclarationSyntax>()(第)。 
VAR semanticModel = compilation.GetSemanticModel(树);
变种类型= semanticModel.GetDeclaredSymbol(classDeclaration)

这可以让你的语义类型的符号,表示语法。 。将它转换为ITypeSymbol如果它没有准备好,并获得它的基本类型属性来获取基本类型



作为吉荣的言论被提到:模块是风马牛不相及的事情在.NET世界。 compilation.Assembly.Modules 也不会涉及到任何类型。在C#中,您不能使用语法来确定一个基本类型,因为如果你有两个部分类声明,但其中只有一个人需要具备的基本类型。唯一的正确的方式做到这一点是语义。


I'm looking to get ancestor from a module's roslyn semanticmodel.

In a class like this :

namespace Name1.Name2
{
    using System;
    ...

    public partial class MyClass : Ancestor<Param1, Param2>
    {
    }
}

So I'm trying to get Ancestor<Param1, Param2> (and later Param1 and Param2).

I'm using this code to create the semanticmodel :

SyntaxTree tree = CSharpSyntaxTree.ParseFile(moduleAutoGenPath);
CompilationUnitSyntax root = (CompilationUnitSyntax)tree.GetRoot();
var nameSpace = ((NamespaceDeclarationSyntax)(root.Members[0])).Name.ToString();
var compilation = CSharpCompilation.Create(nameSpace, new[] { tree }).AddReferences(new MetadataFileReference(typeof(object).Assembly.Location));

I'm looking on compilation.Assembly.Modules but don't find the ancestor..

Am I on the good way? or totally lost?

解决方案

If you're trying to get the base class, do this:

var classDeclaration = someNode.Ancestors().OfType<ClassDeclarationSyntax>().First();
var semanticModel = compilation.GetSemanticModel(tree);
var type = semanticModel.GetDeclaredSymbol(classDeclaration)

This gets you the semantic type symbol that represents that syntax. Cast it to ITypeSymbol if it's not already, and access it's BaseType property to get the base type.

As was alluded to in Jeroen's comments: "modules" are totally unrelated things in the .NET world. compilation.Assembly.Modules wouldn't have anything related to types. In C#, you can't use syntax to determine a base type, because if you have two partial class declarations, only one of them needs to have the base type. The only "correct" way to do it is with semantics.

这篇关于如何获得罗斯林semanticmodel模块的祖先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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