Java 等效于 C# Delegates(将要执行的各种类的方法排队)
TLDR:
是否有与 C# 的 delegates 等效的 Java 版本,可以让我将方法排队各种类并将它们动态添加到队列中?语言构造而不是它的代码.
Is there a Java equivalent of C#'s delegates that will allow me to queue up methods of various classes and add them to the queue dynamically? Language constructs instead of the code for it.
上下文:
我以前使用过 Unity 3D,我喜欢脚本的 Update
方法之类的东西.只需声明该方法即可将其添加到每帧执行的方法列表中.我想在我的 LWJGL 游戏中创建类似的东西.为此,我想使用代表(或等效的东西).是否有任何 Java 语言结构可以让我这样做?我更喜欢包含两个或更多的答案(以便我可以挑选最适合我的代码的)构造和使用它们的方式.我不想要代码,我只想知道从哪里开始.编程中最有趣的部分是解决问题,我不想被剥夺这一点.另外,我不想被确切地告诉如何去做.我想被引导到正确的方向,而不是被那个方向扔到那个目的地.我将如何学习?:-)
I have used Unity 3D before and I love things like the Update
method of scripts. Just declaring the method adds it to the list of methods executed each frame. I want to create something like that in my LWJGL game. For this, I would want to use delegates (or something equivalent to it). Is there any Java language construct that would allow me to do this? I would prefer answers that include two or more (so that I can pick and choose which will be the most optimal for my code) constructs and a way of using them. I don't want the code, I just want to know where to start. The most fun part of programming is working the problem out and I don't want to be deprived of that. Also, I don't want to be told EXACTLY how to do it. I want to be guided in the right direction instead of being thrown in that direction onto that destination. How would I learn? :-)
推荐答案
摘自https://msdn.microsoft.com/en-gb/library/aa288459(v=vs.71).aspx :
C# 中的委托类似于 C 或 C++ 中的函数指针.用一个委托允许程序员封装对方法的引用在委托对象内.然后可以将委托对象传递给可以调用引用方法的代码,无需知道编译时将调用哪个方法.与函数指针不同在 C 或 C++ 中,委托是面向对象、类型安全且安全的.
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
也就是说,Java 没有像 C# 这样的委托.然而,从 Java 8 开始,我们确实有一些函数指针,通过使用 方法引用和功能接口.
That said, Java does not have delegates like C#. However, since Java 8, we do have some sort of function pointers by using method references and functional interfaces.
按照您的礼貌要求,我不会确切地告诉您如何实现此代码,但您应该能够根据这些信息提出解决方案.
As you politely requested, I am not going to tell you exactly how to implement this code, but you should be able to come up with a solution with this information.
相关文章