2015-02-10 46 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

相关问题