views:

79

answers:

3

Hi Everyone,

I get the class name and method name as well as parameters via query string. I don't know what is coming so I can't say lets create this instance or that instance to pass it MethodInfo Invoke method so I need a generic solution. Here is the problem :

string className = Request.QueryString["className"];
string actionMethod = Request.QueryString["actionName"];

so I have to invoke a class method by the info above :

System.Reflection.MethodInfo info = Type.GetType(className).GetMethod(actionMethod);
info.Invoke(obj, null);

But since I don't know what it is coming from the QueryString I can't create an instance of the class of which I want to invoke the method.

How can I get over this problem...

+1  A: 

But since I don't know what it is coming from the QueryString I can't create an instance of the class of which I want to invoke the method.

Why not? You know the type of the object. Just call the default constructor and you have your instance.

An instance method requires an instance of the object. No two ways around that. Looking back at all the instance methods you've written, would it even make sense to call them without an actual object instance behind them?

Anon.
Can you give me an example of something ? If I knew how to do that I wouldn't ask it here :)
Braveyard
`System.Reflection.MethodInfo info = Type.GetType(className).GetMethod(actionMethod); info.Invoke(Activator.CreateInstance(Type.GetType(className)), null);`
Anon.
A: 

Sorry, I am having difficulty understanding the issue here.

If it is you don't know what parameters have been passed into the query string, you could have a constructor / method signature that simply took the query string then parsed it internally.

EDIT

If it is your own class, you can write a method or constructor with a single string or object input, then parse it either with a regex, or a string split on '='

If it is not your class to modify, you will need to create a helper class to act as a factory for the object you are trying to create to do the same thing.

johnc
This is what I am asking, how do I do that ? Thanks...
Braveyard
+1  A: 

If you know the assembly that contains the class you are invoking, you can use Assembly.CreateInstance(string) to create your instance of the class.

Code not tested

object myObject = Assembly.CreateInstance(typeName);
MethodInfo info = Type.GetType(className).GetMethod(actionMethod);
info.Invoke(myObject, null);

http://msdn.microsoft.com/en-us/library/system.reflection.assembly.createinstance.aspx

Kyle Trauberman
You can also use Activator.CreateInstance() to acheive the same results.
Kyle Trauberman