Java 等效于 C# Delegates(将要执行的各种类的方法排队)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39346343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:18:07  来源:igfitidea点击:

Java equivalent of C# Delegates (queues methods of various classes to be executed)

javac#delegates

提问by James Yeoman

TLDR:

域名注册地址:

Is there a Java equivalent of C#'s delegatesthat 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.

是否有 C#委托的 Java 等价物,它允许我将各种类的方法排队并将它们动态添加到队列中?语言构造而不是它的代码。

Context:

语境:

I have used Unity 3D before and I love things like the Updatemethod 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? :-)

我以前用过 Unity 3D,我喜欢像 Update脚本的方法。只需声明该方法即可将其添加到每帧执行的方法列表中。我想在我的 LWJGL 游戏中创建类似的东西。为此,我想使用委托(或类似的东西)。是否有任何 Java 语言结构可以让我这样做?我更喜欢包含两个或更多(以便我可以挑选最适合我的代码的)结构和使用它们的方法的答案。我不想要代码,我只想知道从哪里开始。编程中最有趣的部分是解决问题,我不想被剥夺这一点。此外,我不想被确切地告知如何去做。我想被引导到正确的方向,而不是被朝那个方向扔到那个目的地。我将如何学习?:-)

回答by Michaela Maura Elschner

Actually there is no exact counterpart for delegates in Java. But there are constructs that mimic their behavior.

实际上,Java 中的委托没有确切的对应物。但是有一些结构可以模仿它们的行为。

Java 8

爪哇 8

Functional interfaces

功能接口

The concept that comes closes to delegates in Java 8 is that of functional interfaces.

与 Java 8 中的委托相近的概念是函数式接口的概念

For example, if you have a C# delegate:

例如,如果您有一个 C# 委托:

delegate void Runnable();

in Java, you would create a functional interface like:

在 Java 中,您将创建一个功能接口,如:

@FunctionalInterface
public interface Runnable {
    void run();
}

The nice thing about functional interfaces is they can be used easily in lambda expressions.

函数式接口的好处是它们可以很容易地在lambda 表达式中使用

Example

例子

So, let's suppose you have the following class:

因此,让我们假设您有以下课程:

public class SomeClass {
    public static void someStaticMethod() {
    }

    public void someMethod() {
    }
}

Lambda expressions and method references

Lambda 表达式和方法引用

With Java 8, you get lambda expressions.

使用 Java 8,您可以获得 lambda 表达式。

List<Runnable> queue = new ArrayList<>();
queue.add(() -> someMethod());
queue.add(() -> someStaticMethod());

There is a short-hand named method referencefor this, if you actually simply call a method:

如果您实际上只是调用一个方法,则有一个简短的命名方法引用

List<Runnable> queue = new ArrayList<>();
queue.add(this::someMethod);
queue.add(SomeClass::someStaticMethod);

Java 7

爪哇 7

With Java 7, the only thing you can use is anonymous classes:

在 Java 7 中,您唯一可以使用的是匿名类

List<Runnable> queue = new ArrayList<>();
queue.add(new Runnable() {
    public void run() {
        someMethod();
    }
});
queue.add(new Runnable() {
    public void run() {
        someStaticMethod();
    }
});

I hope this was not too much information, so you can still learn. ;-) However, I like my answer to be useful also for other people looking up this question.

我希望这不是太多的信息,所以你仍然可以学习。;-) 但是,我希望我的回答对其他查找此问题的人也有用。

回答by Jose Ignacio Acin Pozo

Extracted from https://msdn.microsoft.com/en-gb/library/aa288459(v=vs.71).aspx:

摘自https://msdn.microsoft.com/en-gb/library/aa288459(v=vs.71).aspx

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.

C# 中的委托类似于 C 或 C++ 中的函数指针。使用委托允许程序员在委托对象中封装对方法的引用。然后可以将委托对象传递给可以调用引用方法的代码,而不必在编译时知道将调用哪个方法。与 C 或 C++ 中的函数指针不同,委托是面向对象的、类型安全的和安全的。

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.

也就是说,Java 没有像 C# 那样的委托。但是,从 Java 8 开始,我们确实通过使用方法引用和函数接口来获得某种函数指针。

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.

正如您礼貌地要求的那样,我不会确切地告诉您如何实现此代码,但您应该能够根据这些信息提出解决方案。

回答by Hzj_jie

java function interface != c# delegate. From the consumers' side, you won't be able to get any detailed information other than a pure c-style function-pointer. You cannot tell whether a java function interface is binding some objects as a lambda expression or a member function, or just a static method with zero dependencies. I'd say c# delegate provides some very interesting features, may be not that important, to help diagnostic potential program defects like thread-safety of a delegate.

java 函数接口 != c# 委托。从消费者的角度来看,除了纯 c 风格的函数指针之外,您将无法获得任何详细信息。您无法判断 java 函数接口是否将某些对象绑定为 lambda 表达式或成员函数,或者只是具有零依赖关系的静态方法。我想说 c# 委托提供了一些非常有趣的功能,可能不是那么重要,以帮助诊断潜在的程序缺陷,例如委托的线程安全性。