What would be the way to call some method by name, like "Method1", if I've got an Object
and it's Type
?
I want to do something like this:
Object o;
Type t;
// At this point I know, that 'o' actually has
// 't' as it's type.
// And I know that 't' definitely has a public method 'Method1'.
// So, I want to do something like:
Reflection.CallMethodByName(o, "Method1");
Is this somehow possible? I do realize that this would be slow, it's inconvenient, but unfortunately I've got no other ways to implement this in my case.
A method must be created in the class with the name of the method, followed by parentheses (). The method definition consists of a method header and method body. We can call a method by using the following: method_name(); //non static method calling.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.
Once a function is created in Python, we can call it by writing function_name() itself or another function/ nested function. Following is the syntax for calling a function. Syntax: def function_name():
String To Function Using The eval() Function In Python We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ' () ' separated by the addition symbol ' + '.
If the concrete method name is only known at runtime, you can't use dynamic and need to use something like this:
t.GetMethod("Method1").Invoke(o, null);
This assumes, that Method1
has no parameters. If it does, you need to use one of the overloads of GetMethod
and pass the parameters as the second parameter to Invoke
.
You would use:
// Use BindingFlags for non-public methods etc
MethodInfo method = t.GetMethod("Method1");
// null means "no arguments". You can pass an object[] with arguments.
method.Invoke(o, null);
See MethodBase.Invoke
docs for more information - e.g. passing arguments.
Stephen's approach using dynamic
will probably be faster (and definitely easier to read) if you're using C# 4 and you know the method name at compile time.
(If at all possible, it would be nicer to make the type involved implement a well-known interface instead, of course.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With