【问题标题】:How can I use delegates in Java like in C#? [duplicate]如何像在 C# 中一样在 Java 中使用委托? [复制]
【发布时间】:2012-03-19 20:06:38
【问题描述】:

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

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 中使用委托。

【问题讨论】:

  • 看这里:stackoverflow.com/questions/122407/… - 没有真正的代表。
  • 哪个版本的java?我相信新版本的 java 有一些 lambda 支持,这可能会使这段代码更好。
  • @CodeInChaos lambda 计划用于尚未发布的 Java 8...
  • 谢谢。这就是我需要的。您能解释一下如何在我的程序中执行此操作吗?

标签: c# java delegates


【解决方案1】:

你可以使用这样的界面:

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);
}

【讨论】:

    【解决方案2】:

    Java 没有委托,但您可以通过仅使用一种方法声明接口来实现相同的效果。

    interface Function {
        float func(float x);
    }
    
    Functions.Add("y=x", new Function { public float func(float x) { return x; } });
    

    (抱歉可能出现语法错误,我对Java语法不是很熟悉)

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2019-10-07
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多