TutuGeorge
TutuGeorge

Reputation: 2022

How to get methods declared in Base class using Reflection?

I am trying to invoke methods using Reflection in Windwos 8 store application. I tried to get list of all methods from a base class method using this.GetType().GetTypeInfo().DeclaredMethods.

var methodList = base.GetType().GetTypeInfo().DeclaredMethods;

I am able to get all methods declared in the child class and invoke them. But i am unable to get list of methods defined in the base class.
what is wrong with the approach? this project built using .Net for Windows store

Upvotes: 1

Views: 3966

Answers (4)

Yan
Yan

Reputation: 1726

    Type type = GetType(); //In this case Type of current class 
    MethodInfo methodInfo = null;
    do
    {
       methodInfo = type.GetMethod(methodName, BindingFlags.Instance | 
       BindingFlags.NonPublic);
       type = type.BaseType;
    } while (methodInfo == null && type != null);

Upvotes: 0

TutuGeorge
TutuGeorge

Reputation: 2022

GetType().GetRuntimeMethods()

This method gave what i wanted. Got all the methods present inside the object during runtime.

Upvotes: 6

Aron
Aron

Reputation: 15772

Notice that .DeclaredMethods is a property on the class. This is working as intended.

The code you want (I think) is

var methodList = base.GetType().GetMethods();

Upvotes: -1

xanatos
xanatos

Reputation: 111930

You have to do it manually:

public static class TypeInfoEx
{
    public static MethodInfo[] GetMethods(this TypeInfo type)
    {
        var methods = new List<MethodInfo>();

        while (true)
        {
            methods.AddRange(type.DeclaredMethods);

            Type type2 = type.BaseType;

            if (type2 == null)
            {
                break;
            }

            type = type2.GetTypeInfo();
        }

        return methods.ToArray();
    }
}

and then

Type type = typeof(List<int>);
TypeInfo typeInfo = type.GetTypeInfo();
MethodInfo[] methods = typeInfo.GetMethods();

Upvotes: 1

Related Questions