tags:

views:

233

answers:

2

I'm trying this:

Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
    BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);

ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.

How to do that? Thanks.

+2  A: 

You need to fully-qualify the method name, because they're using explicit interface implementation:

Type type = typeof( Application ).GetNestedType( "ThreadContext",
 BindingFlags.NonPublic );
MethodInfo doIdle = type.GetMethod(
 "System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle",
 BindingFlags.NonPublic | BindingFlags.Instance );

For the record, reflecting on non-public members is generally bad practice, but you probably already know that.

EDIT In the spirit of teaching a person to fish, I figured this out by calling GetMethods(...) on the type object, and examining the returned array to see how the methods were named. Sure enough, the names included the complete namespace specification.

Charlie
I did try with UnsafeNativeMethods.IMsoComponent.FDoIdle but forgot the System.Windows.Forms prefix. Thanks for that.
Nicolas Cadilhac
A: 

It's hacky, but this works:

using System;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

public class Test 
{
    static void Main()
    {
        Type clazz = typeof(Application).GetNestedType("ThreadContext", BindingFlags.NonPublic);
        Type iface = typeof(Form).Assembly.GetType("System.Windows.Forms.UnsafeNativeMethods+IMsoComponent");
        InterfaceMapping map = clazz.GetInterfaceMap(iface);
        MethodInfo method = map.TargetMethods.Where(m => m.Name.EndsWith(".FDoIdle")).Single();
        Console.WriteLine(method.Name);
    }
}

There are more surefire ways of matching the target method, but this happens to work this time :)

Jon Skeet
Maybe less obvious than what Charlie wrote, but very interesting.
Nicolas Cadilhac