简体   繁体   English

在运行时调用方法的各种方法是什么?

[英]What the various ways of calling a method at runtime?

I need to call a method on an object but I do not know the method name until runtime. 我需要在对象上调用一个方法,但直到运行时才知道方法名称。

What are the techniques available? 有哪些可用的技术?

(eg GetMethod().Invoke(), delegates, c# 4.0 dynamic) (例如,GetMethod()。Invoke(),委托,C#4.0动态)

Thanks! 谢谢!

The C# 4.0 dynamic functionality is going to be the easiest way to do this. C#4.0 dynamic功能将是最简单的方法。 In a very real sense, dynamic is "just a wrapper" around Reflection. 在一个非常真实的意义上, dynamic是反射的“只是一个包装”。 It's a very good wrapper, though, that is probably your best option. 不过,这是一个非常好的包装,这可能是你最好的选择。

Other ways, in approximately increasing level of difficult: 其他方式,在大约增加的难度下:

  • Using a third-party Reflection library. 使用第三方Reflection库。 Not sure what's out there these days. 不确定这些天有什么。
  • Writing your own Reflection code. 编写自己的反射代码。
  • Use the CodeDOM to create code that calls the method you want to call. 使用CodeDOM创建调用您要调用的方法的代码。
  • Emit IL that does pretty much the same thing as the CodeDOM generated code. 发出与CodeDOM生成的代码几乎相同的东西的IL。
  • Create C# source code that you then compile into an assembly that you can call, which in turn calls the desired method. 创建C#源代码,然后编译成可以调用的程序集,然后调用所需的方法。

The last three are not for the faint of heart. 后三个不适合胆小的人。 Your best bet is to use dynamic or write your own Reflection code. 最好的选择是使用dynamic代码或编写自己的反射代码。 If I had had dynamic three years ago when I was writing code for something similar, I would have used it. 如果我在三年前编写类似的代码时有dynamic ,我会用它。

You can use Reflection to call functions that you do not know the name of until run time. 您可以使用Reflection来调用您不知道运行时名称的函数。 Here's some doc: 这是一些文档:

http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么更好的方法来实例化在运行时指定的类,并在该实例上调用方法? - What better ways are there to instantiate a class specified at runtime, and call a method on that instance? 两种调用方法的方法有何区别? - What is the difference between the two ways to invoke the method? 跟踪任何调用方法的运行时进程? - Trace your runtime process as any method calling? .Net套利运行时类实例化和方法调用 - .Net arbitratry runtime class instantion and method calling 调用异步方法的两种方式。 C# - Two ways of calling asynchronous method. C# 在 C# 中更改方法在运行时返回的内容 - Change what a method returns at runtime in C# 使用Lambda表达式(和仅在运行时已知的Type)调用泛型方法 - Calling a Generic Method using Lambda Expressions (and a Type only known at runtime) 在运行时确定的泛型上调用非泛型方法c# - calling nongeneric method on generic type determined at runtime c# 调用动态方法时,“操作可能会破坏运行时间” - “Operation could destabilize the runtime” when calling dynamic method 除了泛型类之外,还有其他方法可以调用结构的接口方法而不需要装箱吗? - Are there other ways of calling an interface method of a struct without boxing except in generic classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM