hey guys, i would like to call a function with a return value by a string. I ve been searching on the net regarding this question, but all i could find was invoke() and reflection. But i as far as i understand they dont work with function who return a value.
Reflection does work with any kind of method. However I would not recommend building anything on the basis of reflection. There are only a tiny bit of legit usecases. Reflection does essentially bypass the whole OOP model. Also it’s horrible slow and almost always produces garbage.
In this example we get the System.Type of “this”, so the current class this is executed in. If you need to call a method on another object, you have to get the type of that object. Also we pass “this” as the object when we actually invoke the method (and null as the parameters array).
If the method is public and the only method with that name we can simply use GetMethod as we did. However if the method is private we have to pass the right BindingFlags and if there are multiple method overloads (methods with the same name but different arguments) you have to use GetMethod that takes an additional Type array to specify the exact parameter types of the method you want to get.
The Invoke method returns the return value of the method as an “object”. So you have to cast it to the actual type yourself. In the case of a value tyoe lile int, float, Vector3 those types would be boxed.
If a method has “ref” or “out” parameters, those are simply the corresponding elements in the argument array. So when the method call is done, the elements in the argument array that you passed in have been changed by the method.
Generic methods require much more attention as you have to first do the type binding to get the concrete bound method before you can invoke it.
As I said in the beginning there are almost always better approaches to using reflection. You can use a Dictionary of delegates to lookup a certain predefined method. This would be way faster and less error prone.