2015-02-10 112 views
0

我有這樣的方法:無法瞭解如何編寫代碼Func鍵<Func<T1, T2>,T3>

public static IQueryable<char> Test(this string text, Func<Func<char, bool>, int> func) 

這裏char是在文本中找到的字符,布爾確定字符是否被發現,INT返回的索引文本中的字符。

我該怎麼寫這段代碼?謝謝。

+0

'func'是一個函數,它接受一個函數,並返回一個' int'。該輸入函數接受'char'並返回一個'bool' – mihai 2015-02-10 08:56:01

+0

謝謝。我明白這一點。但我不明白如何正確編碼。我需要一個例子。 – 2015-02-10 08:57:42

+1

由於函數中沒有字符源,因此很難檢測字符索引。看起來'func'的類型必須是'Func ,Func ,int>'或'Func ,Func ,int>'。 – 2015-02-10 09:06:22

回答

2

下面是一個例子,它會讓你明白它的作用。
我不知道爲什麼你會需要這個,但可能有一個原因:)。

// These Func's take a char and return a boolean value. 
    Func<char, bool> f1 = (ch) => ch == 'a'; 
    Func<char, bool> f2 = (ch) => ch == 'b'; 

    char chr = 'a'; 

    // This Func takes a function (of the type we saw above) and returns an integer. 
    Func<Func<char, bool>, int> func = (foo) => foo(chr) ? 1 : 0; 

    // Run the complex Func by passing a function as an input param and receiving an integer as a response. 
    int res1 = func(f1); // 1 
    int res2 = func(f2); // 0 

通過你的要求,這裏是另一個例子(我仍然無法找到一個很好的使用,但其它):

string text = "TesTinG"; 
    Func<char, bool> IsCapital = ch => ch == char.ToUpper(ch); 
    int counter = 0; 
    foreach (char chr in text.ToCharArray()) 
    { 
     Func<Func<char, bool>, int> func = fn => fn(chr) ? 1 : 0; 
     counter += func(IsCapital); 
    } 
+0

你好。非常感謝這個代碼和解釋。你能舉一個更詳細的例子來說明如何使用這段代碼嗎? – 2015-02-10 09:32:53

+0

@DeividasGrigas - 我已經添加了另一個在字符串中計算大寫字母的例子。我仍然無法找到與Func ,int>的好用處,但無論如何.. – 2015-02-10 09:39:00

+0

您能否幫助我更多,,,我有這樣的代碼:\t Func f1 =(found ,p)=> new StringParameters(p.Character,p.Text.IndexOf(p.Character,p.Position)!= -1); \t \t \t \t \t行動 comparisonType =(發現,P)=> F1(發現,P).POSITION!= -1? true:false; //新的StringParameters(p。,d))。 Func ,StringParameters> f2 =(c,index)=> text.IndexOf(c,comparisonType);它有什麼問題? – 2015-02-10 17:19:37