c# - 如何像在 C# 中一样在 Java 中使用委托(delegate)?

标签 c# java delegates

<分区>

我写了一些c#代码,实现了几个函数的传递。我为此使用了委托(delegate)。

public delegate float Func(float x);
public Dictionary<string, Func> Functions = new Dictionary<string, Func>();

填写字典:

Functions.Add("y=x", delegate(float x) { return x; });
        Functions.Add("y=x^2", delegate(float x) { return x*x; });
        Functions.Add("y=x^3", delegate(float x) { return x*x*x; });
        Functions.Add("y=sin(x)", delegate(float x) { return (float)Math.Sin((double)x); });
        Functions.Add("y=cos(x)", delegate(float x) { return (float)Math.Cos((double)x); });

我使用这些函数来查找它们的最大值和一些其他任务。

private float maxY(params Func[] F)
    {
        float maxYi = 0;
        float maxY = 0;
        foreach (Func f in F)
        {
            for (float i = leftx; i < rightx; i += step)
            {
                maxYi = Math.Max(f(i), maxYi);
            }
            maxY = Math.Max(maxY, maxYi);
        }
        return maxY;
    }

我如何在 Java 中执行此操作?
我不知道如何在 Java 中使用委托(delegate)。

最佳答案

您可以使用这样的界面:

public static void main(String... args) throws Exception {
    Map<String, Computable> functions = new HashMap<String, Computable>();
    functions.put("y=x", new Computable() {public double compute(double x) {return x;}});
    functions.put("y=x^2", new Computable() {public double compute(double x) {return x*x;}});

    for(Map.Entry<String, Computable> e : functions.entrySet()) {
        System.out.println(e.getKey() + ": " + e.getValue().compute(5)); //prints: y=x: 5.0 then y=x^2: 25.0
    }
}

interface Computable {
    double compute(double x);
}

关于c# - 如何像在 C# 中一样在 Java 中使用委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9514351/

相关文章:

c# - 为什么这个程序不对数组进行排序?

java - 证书未知错误--Java使用的是trustStore

c# - 连接事件处理程序的这两种语法有什么区别?

xcode - 委托(delegate)返回 nil

iOS TableView 不显示数据(调用委托(delegate))

c# - MVC 5 全局用户帐户对象

c# - 多重继承?

c# - 从字符串变量中的名称创建类的对象实例

java - Java 的反射库 : find all classes in a package

java - graph api Restfb - 发布带有链接预览的粉丝专页链接