我有一個函數功能在我的代碼,被聲明是這樣的:使用Func鍵<T>參數
Func<string, int, bool> Filter { get; set; }
我怎樣才能到達字符串和是函數功能的參數,以便在我的代碼使用它們中的int變量?
我有一個函數功能在我的代碼,被聲明是這樣的:使用Func鍵<T>參數
Func<string, int, bool> Filter { get; set; }
我怎樣才能到達字符串和是函數功能的參數,以便在我的代碼使用它們中的int變量?
當函數被調用時,參數只有存在並且它們只在函數中可用。因此,例如:
foo.Filter = (text, length) => text.Length > length;
bool longer = foo.Filter("yes this is long", 5);
這裏,值「是的,這是長」是text
參數的值,而委託執行和同樣價值5是length
參數的價值,同時它的執行。在其他時候,這是一個毫無意義的概念。
你真的想達到什麼目的?如果你能給我們更多的背景,我們幾乎可以肯定地幫助你。
我試圖從用戶那裏得到一個函數,它應該過濾我在我的課堂上的一些元素。 每個元素由一個String和一個int組成,問題是我只有字符串部分,我想在調用這個函數的時候使用這個func來更新int部分。 我知道這不完全是正確的方式,但基於限制,我似乎是唯一的方法。 –
@YoniPlotkin:對不起,我還不清楚發生了什麼事。不應該依賴一個*接受* int的函數來更新它。如果你能提供一個簡短但完整的例子來說明你想要達到的目標,那麼可能會更清楚。 –
對不起,我會盡力解釋 我有一個組件,用戶和服務器類 用戶類看起來像那樣'公共類組件{{; } int Status {get; } }' 和一些更多的功能... 用戶類看起來像這樣: 'public class User { string Id {get; } IDictionary
你可以使用匿名方法:
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 = 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());
}
}
你其實不需要調用Invoke,你只需要'func1(5)'。 – R0MANARMY
認爲'過濾器'是一種方法。它沒有'string'或'int'參數的值。這些值在調用方法時傳遞。 – alf
Func沒有字符串和int *變量*作爲它的參數。它有字符串和int *值*。提供這些值的變量(可能是文字!)應該與Func無關。 – AakashM