首页 > 解决方案 > 如何在不使用 c# 初始化的情况下使用 func deligate?

问题描述

当我在控制台应用程序中运行此代码时,此代码返回“星号”,但我没有在“谓词函数”中初始化“索引”。这是如何运作的?有默认值吗?

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);

标签: c#predicatefunc

解决方案


有两个重载Enumerable.Where

  1. 一个采用常规谓词的形式Func<TSource, Boolean>
  2. 另一个,它接受表单的谓词Func<TSource, Int32, Boolean>并将元素及其索引传递给谓词。

您的代码使用第二个重载。


推荐阅读