How to get module ancestor in roslyn semanticmodel?

拟墨画扇 提交于 2019-12-23 18:13:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23650723/how-to-get-module-ancestor-in-roslyn-semanticmodel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!