功能说明

发布于 2024-07-21 00:41:38 字数 82 浏览 6 评论 0原文

我想知道是否有人可以通过一些清晰的示例来解释 Func是什么以及如何使用它。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夜血缘 2024-07-28 00:41:43

它是一个委托,接受一个 int 作为参数并返回一个 string 类型的值。

下面是它的用法示例:

using System;

class Program
{
    static void Main()
    {
        Func<Int32, String> func = bar;

        // now I have a delegate which 
        // I can invoke or pass to other
        // methods.
        func(1);
    }

    static String bar(Int32 value)
    {
        return value.ToString();
    }
}

It is a delegate that takes one int as a parameter and returns a value of type string.

Here is an example of its usage:

using System;

class Program
{
    static void Main()
    {
        Func<Int32, String> func = bar;

        // now I have a delegate which 
        // I can invoke or pass to other
        // methods.
        func(1);
    }

    static String bar(Int32 value)
    {
        return value.ToString();
    }
}
心头的小情儿 2024-07-28 00:41:43

Func 接受 int 值参数并返回字符串值。 这是一个不需要额外支持方法的示例。

Func<int, string> GetDogMessage = dogAge =>
        {
            if (dogAge < 3) return "You have a puppy!";
            if (dogAge < 7) return "Strong adult dog!";

            return "Age is catching up with the dog!";
        };

string youngDogMessage = GetDogMessage(2);

注意:Func 中的最后一个对象类型(即本例中的“字符串”)是函数返回类型(即不限于基元,而是任何对象)。 因此,Func 接受 int 和 bool 值参数,并返回 float 值。

Func<int, bool, float> WorthlessFunc = (intValue, boolValue) =>
        {
            if(intValue > 100 && boolValue) return 100;

            return 1;
        };
float willReturn1 = WorthlessFunc(21, false);
float willReturn100 = WorthlessFunc(1000, true);

华泰

Func<int, string> accepts an int value parameter and returns a string value. Here's an example where an additional supporting method is unnecessary.

Func<int, string> GetDogMessage = dogAge =>
        {
            if (dogAge < 3) return "You have a puppy!";
            if (dogAge < 7) return "Strong adult dog!";

            return "Age is catching up with the dog!";
        };

string youngDogMessage = GetDogMessage(2);

NOTE: The last object type in Func (i.e. "string" in this example) is the functions return type (i.e. not limited to primitives, but any object). Therefore, Func<int, bool, float> accepts int and bool value parameters, and returns a float value.

Func<int, bool, float> WorthlessFunc = (intValue, boolValue) =>
        {
            if(intValue > 100 && boolValue) return 100;

            return 1;
        };
float willReturn1 = WorthlessFunc(21, false);
float willReturn100 = WorthlessFunc(1000, true);

HTH

别闹i 2024-07-28 00:41:42

Func 吃掉整数并返回字符串。 那么,什么吃掉整数并返回字符串呢? 这个怎么样……

public string IntAsString( int i )
{
  return i.ToString();
}

在那里,我刚刚编写了一个吃整数并返回字符串的函数。 我该如何使用它?

var lst = new List<int>() { 1, 2, 3, 4, 5 };
string str = String.Empty;

foreach( int i in lst )
{
  str += IntAsString(i);
}

// str will be "12345"

我知道这不是很性感,但这是许多技巧所基于的简单想法。 现在,让我们使用 Func 来代替。

Func<int, string> fnc = IntAsString;

foreach (int i in lst)
{
  str += fnc(i);
}

// str will be "1234512345" assuming we have same str as before

我没有对每个成员调用 IntAsString,而是创建了一个名为 fnc 的引用(这些对方法的引用称为 代表)并使用它来代替。 (记住 fnc 吃整数并返回字符串)。

这个例子不是很性感,但是您将看到的大量聪明的东西都是基于函数、委托和 扩展方法

我见过的关于这方面内容的最佳入门书之一是此处。 他还有很多真实的例子。 :)

A Func<int, string> eats ints and returns strings. So, what eats ints and returns strings? How about this ...

public string IntAsString( int i )
{
  return i.ToString();
}

There, I just made up a function that eats ints and returns strings. How would I use it?

var lst = new List<int>() { 1, 2, 3, 4, 5 };
string str = String.Empty;

foreach( int i in lst )
{
  str += IntAsString(i);
}

// str will be "12345"

Not very sexy, I know, but that's the simple idea that a lot of tricks are based upon. Now, let's use a Func instead.

Func<int, string> fnc = IntAsString;

foreach (int i in lst)
{
  str += fnc(i);
}

// str will be "1234512345" assuming we have same str as before

Instead of calling IntAsString on each member, I created a reference to it called fnc (these references to methods are called delegates) and used that instead. (Remember fnc eats ints and returns strings).

This example is not very sexy, but a ton of the clever stuff you will see is based on the simple idea of functions, delegates and extension methods.

One of the best primers on this stuff I've seen is here. He's got a lot more real examples. :)

娇柔作态 2024-07-28 00:41:41

您对代表总体了解吗? 我有一个关于代表和活动的页面,如果没有的话可能会有所帮助,尽管它更适合解释两者之间的差异。

Func只是通用委托 - 通过将类型参数TTResult)替换为相应的来了解它在任何特定情况下的含义在声明中输入参数intstring)。 我还重命名了它以避免混淆:

string ExpandedFunc(int x)

换句话说,Func 是一个委托,它代表一个采用 int 参数并返回 的函数。 >字符串。

Func 通常在 LINQ 中用于投影和谓词(在后一种情况下,TResult 始终为 bool)。 例如,您可以使用 Func 将整数序列投影为字符串序列。 Lambda 表达式通常在 LINQ 中使用来创建相关委托:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文