Reputation: 22854
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.
Upvotes: 9
Views: 506
Reputation: 1503409
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.)
Upvotes: 11
Reputation: 174457
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
.
Upvotes: 11
Reputation: 457292
The easiest way:
dynamic myObject = o;
myObject.Method1();
Upvotes: 8