Is there any way to get Members of a type and all subsequent base types?

↘锁芯ラ 提交于 2019-12-01 06:33:24
JoshVarty

If you're looking for all members whether or not they're accessible:

There is no public API to do this, and internally the Roslyn team's approach is more or less the same as what you've described.

Take a look at the internal extension method GetBaseTypesAndThis(). You could copy this out into your own extension method and use it as follows:

var tree = CSharpSyntaxTree.ParseText(@"
public class A
{
    public void AMember()
    {
    }
}

public class B : A
{
    public void BMember()
    {
    }
}

public class C: B  //<- We will be analyzing this type.
{
    public void CMember()
    {
    }
    //Do you want this to hide B.BMember or not?
    new public void BMember()
    {
    }
}");

var Mscorlib = MetadataReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

var classC = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Last();
var typeC = (ITypeSymbol)model.GetDeclaredSymbol(classC);
//Get all members. Note that accessibility isn't considered.
var members = typeC.GetBaseTypesAndThis().SelectMany(n => n.GetMembers());

If you're looking for members and would like to take accessibility into account:

Take a look at GetAccessibleMembersInThisAndBaseTypes().

If you're trying to build a completion list with members of an accessible type see Roslyn FAQ #5. Sample code is provided here.

It uses SemanticModel.LookupSymbols()

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