C#传递函数作为参数 [英] C# Passing Function as Argument
本文介绍了C#传递函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经写在C#中,做了数值微分的功能。它看起来是这样的:
I've written a function in C# that does a numerical differentiation. It looks like this:
public double Diff(double x)
{
double h = 0.0000001;
return (Function(x + h) - Function(x)) / h;
}
我希望能在任何函数传递,如:
I would like to be able to pass in any function, as in:
public double Diff(double x, function f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
我认为这是可能的代表(也许?),但我不知道如何使用它们。
I think this is possible with delegates (maybe?) but I'm not sure how to use them.
任何帮助将大大AP preciated。
Any help would be greatly appreciated.
谢谢,灰分
推荐答案
使用FUNC上述工程提到,但也有与会代表,执行相同任务,还可以定义命名内意图:
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
这篇关于C#传递函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文