Class *将方法传递到类中

Class *将方法传递到类中,class,function,methods,fitness,Class,Function,Methods,Fitness,我正在编写一个小类,它最大化给定函数F并返回坐标。例如,在最大化下面的一维适应度函数时,我目前有: using System; public static class Program { public static double F(double x) { // for example return Math.Exp(0.4 * Math.Pow(x - 0.4, 2) - 0.08 * Math.Pow(x, 4)); } s

我正在编写一个小类,它最大化给定函数F并返回坐标。例如,在最大化下面的一维适应度函数时,我目前有:

using System;

public static class Program
{
    public static double F(double x)
    {
        // for example
        return Math.Exp(0.4 * Math.Pow(x - 0.4, 2) - 0.08 * Math.Pow(x, 4));
    }

    static void Main(string[] args)
    {

    Metaheutistic Solve = new Metaheutistic;

    Solve.Maximize(Mu, Lambda, Theta);

    }
}
Metaheutistic类中的方法Maximize包含完成所有工作的算法。我的问题是这个算法在一个不知道适应度函数的类中

我是新来C的,如果我在这里喝酒,我愿意从头再来一次。但是,我确实需要将解算器类与适应度函数分开

非常感谢。
*我不确定传递是否是我要寻找的正确术语

您确实可以使用委托将方法传递到函数中,例如:

public delegate double FitnessDelegate(double x);
声明对接受双精度参数并返回双精度参数的函数的委托。然后可以创建对实函数的引用,并将其传递给要调用的Solve方法

public static class Program
{
    public static double F(double x)
    {
        // for example
        return Math.Exp(0.4 * Math.Pow(x - 0.4, 2) - 0.08 * Math.Pow(x, 4));
    }

    static void Main(string[] args)
    {
    FitnessDelegate fitness = new FitnessDelegate(F);
    Metaheutistic Solve = new Metaheutistic;

    Solve.Maximize(fitness);

    }
}
在Solve方法中,您可以像调用方法一样调用此委托,它实际上将执行实际的方法:

class Metaheutistic 
{
  public void Maximise(FitnessDelegate fitness)
  {
    double result = fitness(1.23);
  }
}