views:

42

answers:

1

I have got a variable which contains function hierarchy like:

string str= "fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()))" 

// this hierarchy is coming as a string from database

I have imported System.reflection and used invoke method to invoke it, but it's only working if I have a only one function fun1.

With above function hierarchy it's taking complete expression as a one function name.

I am using this below code to invoke my function hierarchy:

public static string InvokeStringMethod(string typeName, string methodName)
{
// Get the Type for the class
Type calledType = Type.GetType(typeName);

// Invoke the method itself. The string returned by the method winds up in s
String s = (String)calledType.InvokeMember(
                methodName,
                BindingFlags.InvokeMethod | BindingFlags.Public | 
                    BindingFlags.Static,
                null,
                null,
                null);

// Return the string that was returned by the called method.
return s;
}  

Reference: http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx

Please tell me what should I do?

+1  A: 

The problem is the line

string str= fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));

does not represent an expression, or what you call a 'function hierarchy'. Instead, it executes the right-hand side of the assignment evaluates into a string value.

What you are probably looking for is this:

Func<string> f = () => fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));
…
string result = f();

Here, ´f´ is a delegate into which you assign a lambda expression (anonymous method) that can later be executed by invoking the delegate f.

Ondrej Tucny
@Ondrej: actually i am getting values (function hierachy) from table so it will be in string form, not like functions. Please suggest
Rajesh Rolen- DotNet Developer
So the code actually states `string str = "fun1(…)";`, right? But that's a **very different** situation. There is no way to execute such expression using reflection. You will, most probably, have to compile it using CodeDom into a temporary assembly a execute it.
Ondrej Tucny
@Ondrej: Thanks for support
Rajesh Rolen- DotNet Developer
@Rajesh You are welcome. Regarding CodeDom, have a look on this article: http://www.codeproject.com/KB/dotnet/CodeDomDelegates.aspx It covers what you probably need. Consider accepting my answer if it helped :-)
Ondrej Tucny