简体   繁体   中英

C# Func<> - looking for an explanation - not a solution

i am using Math.net, among other methods i use integration, the integration function i use is defined as foloows:

public static double IntegrateComposite(
  Func<double, double> f,
  double intervalBegin,
  double intervalEnd,
  int numberOfPartitions)

yet, my call syntax is:

p = IntegrateComposite(
tau => MyFunction(r, tau, appCfg, Ta, Da) * ProbDensity(tau), 
lowLim, hiLim,  32)

My function is better defined as Func<double, double, double, double, double, double> and not the above Func<double, double> , still everything works fine Why?

This is your the function you pass in, the only input argument is tau.

tau => MyFunction(r, tau, appCfg, Ta, Da) * ProbDensity(tau)

The other varibales r, appCfg, Ta, Da are 'closed over' by a closure

Func<double, double> means

a function which takes 1 argument of type double in, and returns double

That's exactly what your arrow function does, no matter how many external variables are involved into calculation.

Func<T1, T2, T3..., T(n), TResult> is a type that represents a method which takes (n) number of parameters with specified types (could be 0), and returns an object of type TResult .

By Func<double, double> , it specifies that it must be a method which takes one double as a parameter and return a double .

In this example, Lambda function is used (which also can be represented by Func).

tau => {return MyFunction(r, tau, appCfg, Ta, Da) * ProbDensity(tau)},

The only parameter you pass into the lambda function is tau , which can be seen on the left hand side of the arrow. Other variables such as r , tau , appCfg ... are captured variables.

Another example of generic delegates: (obj, e) => {Console.WriteLine(obj)} is passed two variables named obj and e . Unlike your example, It returns nothing. This is represented as Action<T1, T2> which represents a method that returns nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM