Func键的说明Func

2023-09-03 08:28:36 作者:明天会更好

我想知道是否有人能解释什么 Func键< INT,字符串> 以及它是如何被使用的一些明显的例子

I was wondering if someone could explain what Func<int, string> is and how it is used with some clear examples.

推荐答案

您熟悉一般的代表?我有一个关于委托和事件的可能,如果没有帮助页面,虽然它有助于解释之间的差异的详细齿轮两种。

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键&LT; T,TResult&GT; 只是一个普通的委托 - 找出是什么意思,在任何特定情况下通过替换的类型参数的( T TResult )与相应的类型参数的( INT 字符串)的声明。我也改名为避免混淆:

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)

在换句话说, Func键&LT; INT,字符串&GT; 是一个委托其重新presents采取了功能的 INT 参数,并返回一个字符串

In other words, Func<int, string> is a delegate which represents a function taking an int argument and returning a string.

Func键&LT; T,TResult&GT; 常用于LINQ,无论是预测和predicates(在后一种情况下, TResult 总是布尔)。例如,您可以使用 Func键&LT; INT,字符串&GT; 项目整数序列为字符串的序列。 LAMBDA EX pressions 的通常在LINQ用于创建相关的代表:

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);
}

结果:

Value=3
Value=7
Value=10