- Home /
Use a String Variable to Dynamically Invoke a Method
I'm trying to use a string variable to assign which method to call which will then return a Integer value. I can assign the variable using the following simplified example:
int IncomingValue = some.other.method();
int TargetValue = 0;
Update(){
TargetValue = IncomingValue;
}
This returns an updating value based on the result of some.other.method(). This works from a functional standpoint, but what I want to do is assign a string in place of some.other.method() so that I can dynamically assign which method to call in Update(). As in the following example:
string IncomingValue = "some.other.method()";
int TargetValue = 0;
Update(){
TargetValue = IncomingValue;
}
I have found a number of articles referring to the use of Reflection or Delegates, but I can't get any of the examples I've found to work. Basically what I need is some way of Invoking(IncomingValue) and returning the result to TargetValue.
Any suggestions?
Answer by senad · Aug 23, 2012 at 10:01 AM
There is no need for reflection. You want to use delegates to define custom methods.
Your variable will be the type of your delegate instead of string.
Could you give me an example of this? I've found several different methods while researching this issue, and I still haven't been able to implement a working solution.
With delegates your example would look like this:
delegate int input$$anonymous$$ethod() = some.other.method;
int targetValue = 0;
void Update() {
targetValue = input$$anonymous$$ethod();
}
Have a look at this tutorial: http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx
I read through the tutorial you linked and I am completely lost. Example 2 seems like the closest to what I'm trying to accomplish, but I get the error "input$$anonymous$$ethod is a 'Type' but is used like a 'variable'".
Also, if I use your example:
delegate int input$$anonymous$$ethod() = some.other.method;
I get an error expecting a ; before the = sign:
delegate int input$$anonymous$$ethod();
Oh yes, it is true. This is the type declaration:
delegate int Input$$anonymous$$ethodDelegate();
Then you can use it like this:
delegate int Input$$anonymous$$ethodDelegate();
Input$$anonymous$$ethodDelegate input$$anonymous$$ethod = some.other.method;
int targetValue = 0;
void Update()
{
targetValue = input$$anonymous$$ethod();
}