等效于 Java 中的 C# 匿名方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1340231/
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-08-06 15:20:52  来源:igfitidea点击:

Equivalent of C# anonymous methods in Java?

javac#delegatesprocessinganonymous-function

提问by Callum Rogers

In C# you can define delegates anonymously (even though they are nothing more than syntactic sugar). For example, I can do this:

在 C# 中,您可以匿名定义委托(即使它们只不过是语法糖)。例如,我可以这样做:

public string DoSomething(Func<string, string> someDelegate)
{
     // Do something involving someDelegate(string s)
} 

DoSomething(delegate(string s){ return s += "asd"; });
DoSomething(delegate(string s){ return s.Reverse(); });

Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).

是否可以在 Java 中传递这样的代码?我正在使用处理框架,它有一个很旧的 Java 版本(它没有泛型)。

采纳答案by Michael Lloyd Lee mlk

Pre Java 8:

Java 8 之前:

The closest Java has to delegates are single method interfaces. You could use an anonymous inner class.

与委托最接近的 Java 是单方法接口。您可以使用匿名内部类。

interface StringFunc {
   String func(String s);
}

void doSomething(StringFunc funk) {
   System.out.println(funk.func("whatever"));
}

doSomething(new StringFunc() {
      public String func(String s) {
           return s + "asd";
      }
   });


doSomething(new StringFunc() {
      public String func(String s) {
           return new StringBuffer(s).reverse().toString();
      }
   });


Java 8 and above:

Java 8 及更高版本:

Java 8adds lambda expressions to the language.

Java 8向该语言添加了 lambda 表达式。

    doSomething((t) -> t + "asd");
    doSomething((t) -> new StringBuilder(t).reverse().toString());

回答by Gregory Mostizky

Not exactly like this but Java has something similar.

不完全是这样,但 Java 有类似的东西。

It's called anonymous inner classes.

它被称为匿名内部类。

Let me give you an example:

让我给你举个例子:

DoSomething(new Runnable() {
   public void run() {
       // "delegate" body
   }
});

It's a little more verbose and requires an interface to implement, but other than that it's pretty much the same thing

它有点冗长,需要一个接口来实现,但除此之外,它几乎是一样的

回答by John Feminella

Is it possible to pass code like this in Java? I'm using the processing framework, which has a quite old version of Java (it doesn't have generics).

是否可以在 Java 中传递这样的代码?我正在使用处理框架,它有一个很旧的 Java 版本(它没有泛型)。

Since the question asked about the Processing-specific answer, there is no direct equivalent. But Processing uses the Java 1.4 language level, and Java 1.1 introduced anonymous inner classes, which are a rough approximation.

由于问题是关于特定于处理的答案,因此没有直接的等价物。但是Processing 使用的是Java 1.4 语言级别,Java 1.1 引入了匿名内部类,这是一个粗略的近似。

回答by Jesper

Your example would look like this in Java, using anomymous inner classes:

您的示例在 Java 中看起来像这样,使用匿名内部类:

interface Func {
    String execute(String s);
}

public String doSomething(Func someDelegate) {
    // Do something involving someDelegate.execute(String s)
}

doSomething(new Func() { public String execute(String s) { return s + "asd"; } });
doSomething(new Func() { public String execute(String s) { return new StringBuilder(s).reverse().toString(); } } });

回答by JAN

For example :

例如 :

public class Delegate
{
    interface Func
    {
        void execute(String s);
    }

    public static void doSomething(Func someDelegate) {
        someDelegate.execute("123");
    }

    public static void main(String [] args)
    {

        Func someFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Bla Bla :"  + s);
            }
        };

        Func someOtherFuncImplementation = new Func() 
        {
            @Override
            public void execute(String s) {
                System.out.println("Foo Bar:"  + s);
            }
        };


        doSomething(someFuncImplementation);
        doSomething(someOtherFuncImplementation);
    }
}

Output :

输出 :

Bla Bla :123

Foo Bar:123

布拉布拉:123

福吧:123

回答by JAN

You have all forgotten here that a C# delegate first of all - is thread safe. These examples are just for a single thread App..

在这里你们都忘记了 C# 委托首先是线程安全的。这些示例仅适用于单线程应用程序..

Most of the contemporary Apps are written on multithreaded concept.. So no one answer is the answer.

大多数当代应用程序都是基于多线程概念编写的。所以没有一个答案是答案。

There is not an equivalent in Java

Java 中没有等价物