Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a method by its "name"?

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.

like image 820
Yippie-Ki-Yay Avatar asked May 11 '11 15:05

Yippie-Ki-Yay


People also ask

How do you call a method?

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.

How do you call a method in a string name?

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.

How do you call a method in Python?

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():

How do you call a function by its string name in Python?

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 ' + '.


2 Answers

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.

like image 174
Daniel Hilgarth Avatar answered Oct 17 '22 07:10

Daniel Hilgarth


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.)

like image 38
Jon Skeet Avatar answered Oct 17 '22 07:10

Jon Skeet