System.Func
Added in .NET 3.5
The Func delegate is used for methods that accept one or more arguments and return a value.
An anonymous function is an inline statement or expression that can be used wherever a delegate type is expected.
A delegate with a specific signature can be declared using the Func type.
The last parameter of the Func delegate is the output parameter or result parameter.
System.Func<string, string> delegate_variable = delegate(string param1)
{ return parameter.ToUpper(); }
instead of
delegate string Delegate_Type(string x);
Delegate_Type delegate_variable delegate(string param1)
{ return parameter.ToUpper(); }
Scalar Function Example
This transforms an array by applying a delegate to each element in the array.
public class GenericProperties
{
public delegate T MyTransformer(T myArgument);
public static void MyTransform(T[] values, MyTransformer transform)
{
for (int i=0; I < values.Length; i++)
{
values[i] = transform(values[i]);
}
}
}
static double Log(double t) { return Math.Log(t); }
static void Main()
{
double[] arr = { 2.0, 4.0, 6.0 };
GenericProperties<double>.MyTransform(arr, Square);
foreach (double d in arr)
{
System.Console.Write(d + ",");
}
GenericProperties<double>.MyTransform(arr, Log);
foreach (double d in arr)
{
System.Console.Write(d + ",");
}
}
This delegate takes multiple input parameters (T1, T2, etc) and one output parameter (TResult)
In .NET 3.5 the following signatures were available.
public delegate TResult System.Func<out TResult>(T arg);
public delegate TResult System.Func<in T, out TResult>(T arg);
public delegate TResult System.Func<in T1, T2, out TResult>(T arg);
public delegate TResult System.Func<in T1, T2, T3, out TResult>(T arg);
public delegate TResult System.Func<in T1, T2, T3, T4, out TResult>(T arg);
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext