0

So I'm calling a method from my dll using this.

string sp = "dynamicmethodname";

Type TypeObj = typeof(DLLclass);
Object MyObj = Activator.CreateInstance(TypeObj);
TypeObj.InvokeMember(sp, BindingFlags.InvokeMethod | BindingFlags.Default, null, MyObj, new Object[] { gp });  

it will work if my method is just under my public class. But when I tried to do something like this.

public class Test {
   public static class Met1{
     public static void _Validate(string gp){
      functions here.....
    }
  }
}

The invokemember method won't reach my _Validate method anymore. I wonder why it won't work anymore.

Eraniichan
  • 121
  • 1
  • 10
  • 1
    You can't create an instance of a static class - does `Activator.CreateInstance` actually work? – Charleh Jun 24 '15 at 08:34
  • 1
    If you want to call a method on a static class you can just use invoke directly (and pass null to the instance param): see here http://stackoverflow.com/questions/614863/activator-and-static-classes – Charleh Jun 24 '15 at 08:35
  • @Charleh Yah it works if my method is just under my public class Test. But I need to pass parameters for my method... – Eraniichan Jun 24 '15 at 08:44
  • You can still pass parameters with Invoke...https://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx - more specifically this overload: https://msdn.microsoft.com/en-us/library/4k9x6bc0.aspx , the `Object[]` is params.. – Charleh Jun 24 '15 at 09:05

1 Answers1

0

Full example of what @Charleh wrote:

public class Test
{
    public static class Met1
    {
        public static void _Validate(string gp)
        {
            Console.WriteLine(gp);
        }
    }
}

MethodInfo method = typeof(Test.Met1).GetMethod("_Validate");
// Or 
// MethodInfo method = typeof(Test.Met1).GetMethod("_Validate", BindingFlags.Static | BindingFlags.Public);
// or
// MethodInfo method = typeof(Test.Met1).GetMethod("_Validate", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);

method.Invoke(null, new object[] { "Hello world " });

Compiled: https://ideone.com/JIoHar

xanatos
  • 109,618
  • 12
  • 197
  • 280