你怎么用它的"名字"来称呼方法?

Yip*_*Yay 9 c# reflection object

通过名称调用某个方法的方法是什么,比如"Method1",如果我有一个Object,那就是它Type

我想做这样的事情:

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");
Run Code Online (Sandbox Code Playgroud)

这有点可能吗?我确实意识到这会很慢,这很不方便,但不幸的是,在我的情况下,我没有其他方法可以实现这一点.

Jon*_*eet 12

你会用:

// 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);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅MethodBase.Invoke文档 - 例如传递参数.

dynamic如果您使用C#4并且在编译时知道方法名称,则使用Stephen的方法可能会更快(并且更容易阅读).

(如果可能的话,那么使所涉及的类型实现一个众所周知的界面会更好.)


Dan*_*rth 11

如果具体方法名称仅在运行时已知,则无法使用动态,需要使用以下内容:

t.GetMethod("Method1").Invoke(o, null);
Run Code Online (Sandbox Code Playgroud)

这假设Method1没有参数.如果是,则需要使用其中一个重载GetMethod并将参数作为第二个参数传递给Invoke.

  • 我的回答实际上是编译. (4认同)

Ste*_*ary 8

最简单的方法:

dynamic myObject = o;
myObject.Method1();
Run Code Online (Sandbox Code Playgroud)

  • "而且我知道't'肯定有一个公共方法'Method1'` - 我把它解释为编译时知识. (3认同)
  • 并非所有人都在使用C#4.0. (2认同)
  • 这假设您在编译时知道该方法. (2认同)