[英]Using Func<T> parameters
我的代碼中有一個Func,聲明如下:
Func<string, int, bool> Filter { get; set; }
我怎樣才能到達作為Func參數的字符串和int變量,以便在我的代碼中使用它們?
參數僅在調用函數時存在 ...並且它們僅在函數內可用。 例如:
foo.Filter = (text, length) => text.Length > length;
bool longer = foo.Filter("yes this is long", 5);
這里,值“yes this is long”是委托執行時 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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.