Non-static method requires a target

  • Thread starter Thread starter TJO
  • Start date Start date
T

TJO

I am trying to load an assembly, instantiate a class and invoke a
non-static void method using the following code:

I am getting the error "Non-static method requires a target" on the
InvokeMember method but don't see why. Can anyone shed light on this??




Assembly testAssembly =
Assembly.LoadFile(@"C:\STProjects\..\MyAssembly.dll");

Type testType =
testAssembly.GetType(this._cmbo_TestClasses.Text.Trim());



object[] args = new object[]{"myparam"};

SmartMI_TestClasses.HDDUtilization HDDtest =
(SmartMI_TestClasses.HDDUtilization)
testAssembly.CreateInstance(
testType.Name,
false, BindingFlags.Default, null,
args, null, null);


object o = testType.InvokeMember(
"_ExecuteTest",
BindingFlags.InvokeMethod,
null, HDDtest, null);
 
Maybe CreateInstance returned null because it couldn't find the class
testType.Name in testAssembly?
 
Otherwise, try getting the MethodInfo from the Type for the method that
you want to invoke, check that it's finding it (not null), and then use
MethodInfo.Invoke
 
The CreateInstance method is not returning the object as I expected.
Instead it is a null reference!?? I am not sure how to use the
MethodInfo in this situation. MSDN docs are not providing much
guidance. Any code snippets or other suggestions HIGHLY welcome here.
 
This is some simple code that works:

object[] args = new object[]{machine[0].ToString()};

object
ob = Activator.CreateInstance(testType, args);

The only problem is when I attempt to cast ob to the proper class I get
a cast exception error.

Anyone see why?
 
This one should work:

//create instance assuming default constructor
object obj = testType.InvokeMember(null, BindingFlags.Public |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
//call method now
tp.InvokeMember("_ExecuteTest", BindingFlags.InvokeMethod, null, obj, null);
 
This did work thank you.

Why does the following code not work once the obj is instantiated??

myclass c = (myclass)obj;

I am now getting invalid cast!?
 
obj is an instance of a class for which you have no direct reference. In
VB.NET you could just use late binding and call the method directly
(obj.myMethod), but C# doesn't support late binding at the language level. As
far as I know, you can only use this instance through reflection.
 
Back
Top