Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection: Get info for all members of class and base classes

Tags:

c#

reflection

When I run the following code, it only returns a MethodInfo/FieldInfo/etc. that belongs directly to the Type that I'm searching for the info object in. How do I find the info object regardless of the fact that it resides in a base class and could be private?

obj.GetType().GetMethod(methodName, bindingFlags);
like image 689
bsara Avatar asked Nov 16 '25 21:11

bsara


1 Answers

Well, you answered your own question, but as far as I understood, you main requirement is How do I find the info object regardless of where it is found in the hierarchy?

You don't need recursion here to get all members in the full hierarchy. You can use GetMembers function on a Type and it will return all members including all base classes.

Next code example demonstrates this:

var names = 
    typeof(MyClass).GetMembers()
                   .Select (x => x.Name);

Console.WriteLine (string.Join(Environment.NewLine, names));

for such structure

class MyClass : Base
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

class Base
{
    public string Name { get; set; }
}

returns

get_Name
set_Name
get_Surname
set_Surname
get_Name
set_Name
ToString
Equals
GetHashCode
GetType
.ctor
Name
Surname

note that get_Name accessor for auto-property appears twice because MyClass hides Name property of the base class. Also note ToString, GetType and other methods, defined in object class

like image 102
Ilya Ivanov Avatar answered Nov 18 '25 10:11

Ilya Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!