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?
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());
The following is the definition for GetBaseTypesAndThis()
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
To check for accessibility put a where condition in the following line to check for accessibility:
typeC.GetBaseTypesAndThis().SelectMany(n => n.GetMembers().Where(x => x.DeclaredAccessibility == Accessibility.Public));`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With