Are you familiar with delegates in general? I have a page about delegates and events which may help if not, although it's more geared towards explaining the differences between the two.
Func<T, TResult>
is just a generic delegate - work out what it means in any particular situation by replacing the type parameters (T
and TResult
) with the corresponding type arguments (int
and string
) in the declaration. I've also renamed it to avoid confusion:
string ExpandedFunc(int x)
In other words, Func<int, string>
is a delegate which represents a function taking an int
argument and returning a string
.
Func<T, TResult>
is often used in LINQ, both for projections and predicates (in the latter case, TResult
is always bool
). For example, you could use a Func<int, string>
to project a sequence of integers into a sequence of strings. Lambda expressions are usually used in LINQ to create the relevant delegates:
Func<int, string> projection = x => "Value=" + x;
int[] values = { 3, 7, 10 };
var strings = values.Select(projection);
foreach (string s in strings)
{
Console.WriteLine(s);
}
Result:
Value=3
Value=7
Value=10
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…