开发者

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

Wha开发者_运维知识库t 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.


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


The easiest way:

dynamic myObject = o;
myObject.Method1();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜