unknown method

  • Thread starter Thread starter Frank
  • Start date Start date
F

Frank

Hello,
I want to execute MethodA of a objectB. I don't know what kind of class
objectB is, I only know it has a method called methodA. How can I do this?
I looked into the Activator class, but then you still need the
classdefinition and I don't have that!

Thanks for the time
Frank
 
Hi Frank,

You will have to implement some Reflection into your code. for example:

<code>
using System.Reflection;
..
..
..

public void InvokeMethodA ( object objectToInvoke )
{
Type objectType = objectToInvoke.GetType();
MethodInfo methodA = objectType.GetMethod( "MethodA" );

methodA.Invoke ( objectToInvoke, new object[] {} )
}
</code>
 
Frank said:
I want to execute MethodA of a objectB. I don't know what kind of class
objectB is, I only know it has a method called methodA. How can I do this?
I looked into the Activator class, but then you still need the
classdefinition and I don't have that!

The best thing would be for MethodA to be encapsulated into an
interface that objectB implements. You could then cast to that
interface and call the method. Otherwise, you can use Type.GetMethod to
get the right MethodInfo, and then invoke it.
 
I'll try this. Thanks
Frank

Patrik Löwendahl said:
Hi Frank,

You will have to implement some Reflection into your code. for example:

<code>
using System.Reflection;
.
.
.

public void InvokeMethodA ( object objectToInvoke )
{
Type objectType = objectToInvoke.GetType();
MethodInfo methodA = objectType.GetMethod( "MethodA" );

methodA.Invoke ( objectToInvoke, new object[] {} )
}
</code>

--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'

Hello,
I want to execute MethodA of a objectB. I don't know what kind of class
objectB is, I only know it has a method called methodA. How can I do this?
I looked into the Activator class, but then you still need the
classdefinition and I don't have that!

Thanks for the time
Frank
 
That worked fine, very easy.
Thanks
Frank
Patrik Löwendahl said:
Hi Frank,

You will have to implement some Reflection into your code. for example:

<code>
using System.Reflection;
.
.
.

public void InvokeMethodA ( object objectToInvoke )
{
Type objectType = objectToInvoke.GetType();
MethodInfo methodA = objectType.GetMethod( "MethodA" );

methodA.Invoke ( objectToInvoke, new object[] {} )
}
</code>

--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'

Hello,
I want to execute MethodA of a objectB. I don't know what kind of class
objectB is, I only know it has a method called methodA. How can I do this?
I looked into the Activator class, but then you still need the
classdefinition and I don't have that!

Thanks for the time
Frank
 
I strongly agree with the Interface bit ... That would be the ideal
solution where reflection would be the last way out..
 
Back
Top