Reflection and Abstract classes

S

shiry

Hi,

Can anyone tell me how can I get a protected method of an abstract
class using reflection?

I need to invoke a method like this and I was trying invokeMember on
the type of the derived class with an object of the derived class. This
doesn't work.
I cannot perform this on the abstract class since I cannot instantiate
it.

What am I doing wrong?

Thanks.
 
D

Dave Sexton

Hi,

// create an instance on which the method will be invoked
DerivedClass obj = new DerivedClass();

// get the Type that defines the method (AbstractClass)
Type type = typeof(AbstractClass);

// get the method
MethodInfo m = type.GetMethod("AMethod",
BindingFlags.NonPublic | BindingFlags.Instance);

// invoke the method on the instance of DerivedClass
m.Invoke(obj, null);
 
S

shiry

Thanks! It works great.

Dave said:
Hi,

// create an instance on which the method will be invoked
DerivedClass obj = new DerivedClass();

// get the Type that defines the method (AbstractClass)
Type type = typeof(AbstractClass);

// get the method
MethodInfo m = type.GetMethod("AMethod",
BindingFlags.NonPublic | BindingFlags.Instance);

// invoke the method on the instance of DerivedClass
m.Invoke(obj, null);
 

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