需要使用func了解以下代码

时间:2018-12-24 07:45:40

标签: c#

我是新来的代表。今天,我在此Link上看到了一个代码。由于我是c#的新手,特别是对于代理人,我无法理解以下代码。

public static void Main()
   {
      Func<String, int, bool> predicate = (str, index) => str.Length == index;

      String[] words = { "orange", "apple", "Article", "elephant", "star", "and" };
      IEnumerable<String> aWords = words.Where(predicate).Select(str => str);

      foreach (String word in aWords)
         Console.WriteLine(word);
   }

以上代码的输出为“ star”。 AS谓词期望使用参数,但是在这种情况下,我们没有传递任何参数。您的评论将不胜感激。

4 个答案:

答案 0 :(得分:4)

首先,有一个函数定义:

 Func<String, int, bool> predicate = (str, index) => str.Length == index;

如果字符串的长度等于索引,则其读为“给定的字符串表示为str,而索引的表示形式为index返回true,否则返回false

遇到可枚举管道时:

IEnumerable<String> aWords = words.Where(predicate).Select(str => str);

您在上面传递了此函数定义,类似于:

words.Where((element, index) => element.Length == index).Select(str => str);

并且您会看到只有元素“ star”符合该条件,即“ star”的长度为4 ,并且其索引也是4

关于您的困惑:

  

AS谓词期望使用参数,但是在这种情况下,我们不能   传递任何参数。

请注意,在涉及LINQ时,我们仅指定“内容”,而“如何”是实现细节。因此在上述代码中,Where子句会将每个元素及其索引传递给predicate函数。


另一方面,Select是多余的,仅IEnumerable<String> aWords = words.Where(predicate)就足够了。

答案 1 :(得分:0)

让我们从第一行开始检查这段代码。

 domains
      list=integer*
   predicates
      readlist(list)
   clauses
      readlist([H|T]):-
         write("> "),
         readint(H),!,
         readlist(T).
      readlist([ ]).

在这里,我们仅声明了一个名为 predicate 的变量。这是一种特殊的变量,其值是一个函数,该函数接收string和int类型的两个参数,并且期望返回布尔值。但是该功能的主体在哪里?等号后。 (str,index)是参数,主体只是参数str的长度与参数index的值之间的比较。 => str.Length == index 如果条件匹配,则返回true,否则返回false

现在我们了解了委托的声明,下一个问题是我们在哪里使用它。这甚至更简单。只要需要与委托人匹配的函数,就可以使用它。

现在Where IEnumerable extension的重载就是这样,因此我们可以简单地将 predicate 变量放在该位置并调用Where扩展名

答案 2 :(得分:0)

简而言之,代码只是说:“选择长度等于索引的所有单词”

string[] words = { "orange", "apple", "Article", "elephant", "star", "and" };

// select all words where the length equals the index
var aWords = words.Where((str, i) => str.Length == i);

foreach (var word in aWords)
   Console.WriteLine(word);

Where<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

  

根据谓词过滤值序列。每个元素的   谓词函数的逻辑中使用了索引。

Func<T1,T2,TResult> Delegate

  

封装一个具有两个参数并返回值的方法   TResult参数指定的类型。

所以唯一的魔力是Func

Func<String, int, bool> predicate = (str, index) => str.Length == index;

(在这种情况下)只是一种奇特的写作方式

public bool DoSomething(string str, int index)
{
    return str.Length == index;
}

本质上,它只是一个委托,与Action不同,它能够返回值

Delegates (C# Programming Guide)

  

委托是一种类型,它代表对方法的引用   特定的参数列表和返回类型。当您实例化一个   委托,您可以将其实例与具有   兼容的签名和返回类型。您可以调用(或调用)   通过委托实例的方法。

答案 3 :(得分:0)

为简化起见,

var aWords = words.Where(str => str.Length == 4);

与以下相同:

Func<string, bool> predicate = str => str.Length == 4;
var aWords = words.Where(predicate);

predicate()执行它,不带predicate的{​​{1}}可以将其作为参数传递给方法。


在C#7中引入的local functions(可以在其他函数中声明的函数)可以是:

()
相关问题