问题
I have an `ITypeSymbol' object. If I call GetMembers, it gives me the members of the current type, not the base. I know I can dig it using BaseType property and have some iterative code to fetch all the properties.
Is there any easier way to fetch all members regardless of level at the inheritance hierarchy?
回答1:
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()
来源:https://stackoverflow.com/questions/30443616/is-there-any-way-to-get-members-of-a-type-and-all-subsequent-base-types