【发布时间】:2019-07-09 06:29:58
【问题描述】:
我是编程新手。我想用yield 关键字实现一个程序。所以,我创建了一个new List 并要求用户通过控制台输入列表值。
在那之后,我在该列表中实现了foreach。并检查条件,列表中是否存在“特定的预期字符串”与 yield 关键字。
我的期望:
- 循环浏览现有列表。
- 借助“yield”关键字检查列表中是否存在“TamilSelvi”。
- 最后,返回匹配的字符串
我的实现:
-
我已经创建了一个列表。
-
将该列表的容量设置为 6。
-
通过控制台为用户获取输入。
-
最后,在 yield 的帮助下检查用户输入的列表是否包含“TamilSelvi”。
using System; using System.Collections.Generic; using System.Collections; namespace yield_Keyword_in_C_Sharp { class Program { static void Main(string[] args) { Console.WriteLine("Implementation of Yield Keyword in C# with List"); Console.WriteLine(); // Create a List List<string> names = new List<string>(); names.Capacity = 6; Console.WriteLine("Get the Input From the User"); Console.WriteLine(); //Get the List Input From the User foreach (string n in names) { string temp = Console.ReadLine(); if (temp.Length != 0 && temp != " " && temp != " ") { names.Add(temp); temp = string.Empty; } } //Print the List values entered by the user in the Console Window Console.WriteLine("Print the Values Entered by the User"); Console.WriteLine(); foreach (string na in names) { Console.WriteLine(na); } Console.WriteLine(); Console.WriteLine("Get the TamilSelvi in above list with the help of yield keyword"); display(names); void display(List<string> words) // display method implementation { foreach (string word in words) { if (word == "TamilSelvi") yield return word; } } Console.WriteLine(); Console.ReadLine(); } } }
预期结果:
C#用List实现yield关键字
从用户那里获取输入
Thirunavukkarasu
泰米尔语
文尼拉
萨巴里娜坦
Muthuprakash
穆塔拉桑
打印用户输入的值
Thirunavukkarasu
泰米尔语
文尼拉
萨巴里娜坦
Muthuprakash
穆塔拉桑
借助 yield 关键字获取上面列表中的 TamilSelvi
泰米尔语
实际结果: 应用程序无法构建。面临以下错误。
错误:
'display(List words)' 的主体不能是迭代器块,因为 'void' 不是迭代器接口类型。
【问题讨论】:
-
方法
Yield的返回值为IEnumerable<T> -
返回类型 pf 显示函数必须是可枚举的字符串,并且您应该遍历该返回值才能正常工作。希望这会对你有所帮助。
标签: c# yield-return