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.
任何帮助将不胜感激.
推荐答案
使用上面提到的 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屋!
查看全文