tags:

views:

46

answers:

3

I have a dll file, and I took an object from it and called the functions inside this dll by the object, like this:

Command testClass = (Command)assembly.CreateInstance(creatObject);                
testClass.Execute();

I used reflection for some reason. So I need to use invoke function & set values for variables, then calling the basic function Execute.

Previously I wrote the following:

object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
testClass.Execute();

but it wasn't useful for me.

I used the following:

object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments);
object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);

I just want to ask if this is right, to calling the execute in this way, and by the way it works!

+1  A: 

It's not right, why do you use Reflection, provide a common interface and call the method directly. If you don't know why you use reflection then it's wrong :)

If you are implementing a extensible system, perhaps MEF would be better?

Ion Todirel
+2  A: 

Calling methods using Reflection the way you use it is "okay" as long as you know what you're doing. There are quite a few things to consider when using Reflection:

  • It is unsafe - you can very easily make a mistake - if you change the method name, you won't be notified by the compiler and you'll discover that at runtime
  • It is slow - Reflection is simply inefficient - calling a method is slower by orders of magnitude.

If you need to do this only rarely, then it may be fine. However, your initial approach using a shared base class Command appears to be a much better idea to me. Could you clarify why you decided to use Reflection, so that we can (perhaps) suggest a better way?

If you need dynamic invocation, you could also consider using C# 4.0 dynamic, which does all this stuff behind the scene for you and is more efficient than simple Reflection. However, you should still have a very good reason for doing this.

Tomas Petricek
A: 

Thanks for your answers, sure i know why i used Reflection. Because i need to set the values for a function ( setValues(i, j..etc) )in run time, and these parameters and their names are different from dll to another. then i have to invoke this function with its current values, & finally run another function named ( Execute() ) with the same current values, which could be changed from execute to another for the program! so when i just used:

object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments); testClass.Execute();

the execute didnt work with the run time values which been entered. But by this :

object returnValue = objectType.GetMethod("setValues").Invoke(classObject, arguments); object returnValue1 = objectType.GetMethod("Execute").Invoke(classObject, null);

it works. So i just want to be sure, that my work is right and not only suitable for my case!

Alaa'