使用 Func 参数

本文关键字:参数 Func 使用 | 更新日期: 2023-09-27 18:37:22

我的代码中有一个 Func,声明如下:

Func<string, int, bool> Filter { get; set; }

如何访问作为 Func 参数的字符串和 int 变量,以便在我的代码中使用它们?

使用 Func<T> 参数

参数仅在调用函数时存在...它们仅在函数中可用。所以例如:

foo.Filter = (text, length) => text.Length > length;
bool longer = foo.Filter("yes this is long", 5);

在这里,值"是的,这很长"是委托执行时text参数的值,同样,值 5 是执行length参数的值。在其他时候,这是一个毫无意义的概念。

你真正想实现的目标是什么?如果您能给我们更多的背景信息,我们几乎可以肯定可以更好地帮助您。

您可以使用匿名方法:

Filter = (string s, int i) => {
    // use s and i here and return a boolean
};

或标准方法:

public bool Foo(string s, int i)
{
    // use s and i here and return a boolean
}

然后,您可以将 Filter 属性分配给此方法:

Filter = Foo;

在此处查看此示例 - http://www.dotnetperls.com/func

using System;
class Program
{
    static void Main()
    {
    //
    // Create a Func instance that has one parameter and one return value.
    // ... Parameter is an integer, result value is a string.
    //
    Func<int, string> func1 = (x) => string.Format("string = {0}", x);
    //
    // Func instance with two parameters and one result.
    // ... Receives bool and int, returns string.
    //
    Func<bool, int, string> func2 = (b, x) =>
        string.Format("string = {0} and {1}", b, x);
    //
    // Func instance that has no parameters and one result value.
    //
    Func<double> func3 = () => Math.PI / 2;
    //
    // Call the Invoke instance method on the anonymous functions.
    //
    Console.WriteLine(func1.Invoke(5));
    Console.WriteLine(func2.Invoke(true, 10));
    Console.WriteLine(func3.Invoke());
    }
}