Non-static method requires a target

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);
 
B

Bruce Wood

Maybe CreateInstance returned null because it couldn't find the class
testType.Name in testAssembly?
 
D

Deviant

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
 
T

TJO

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.
 
T

TJO

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?
 
G

Guest

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);
 
G

Guest

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!?
 
G

Guest

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top