问题
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