C# 如何修复“由于“string”不是迭代器接口类型,“display(List)”的主体不能是迭代器块”?
我是编程新手。我想用yield关键字实现一个程序。因此,我创建了一个新列表,并要求用户通过控制台输入列表值 在此之后,我实现了该列表的foreach。并检查条件,列表中是否存在特定的预期字符串以及yield关键字 我的期望: 循环浏览现有列表。 借助yield关键字检查列表中是否有泰米尔塞尔维。 最后,返回匹配的字符串 我的实施: 我已经创建了一个列表。 将该列表的容量设置为6。 通过控制台获取用户的输入。 最后,在yield的帮助下,检查用户输入的列表中是否有泰米尔塞尔维值C# 如何修复“由于“string”不是迭代器接口类型,“display(List)”的主体不能是迭代器块”?,c#,yield-return,C#,Yield Return,我是编程新手。我想用yield关键字实现一个程序。因此,我创建了一个新列表,并要求用户通过控制台输入列表值 在此之后,我实现了该列表的foreach。并检查条件,列表中是否存在特定的预期字符串以及yield关键字 我的期望: 循环浏览现有列表。 借助yield关键字检查列表中是否有泰米尔塞尔维。 最后,返回匹配的字符串 我的实施: 我已经创建了一个列表。 将该列表的容量设置为6。 通过控制台获取用户的输入。 最后,在yield的帮助下,检查用户输入的列表中是否有泰米尔塞尔维值 using Sys
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();
}
}
}
预期结果:
用List实现C语言中的Yield关键字
从用户那里获取输入
第三轮卡拉苏
泰米尔塞尔维
文尼拉
萨巴拉尼坦
穆图普拉卡什
穆塔拉桑
打印用户输入的值
第三轮卡拉苏
泰米尔塞尔维
文尼拉
萨巴拉尼坦
穆图普拉卡什
穆塔拉桑
使用yield关键字获取上面列表中的泰米尔塞尔维
泰米尔塞尔维
实际结果:
应用程序无法生成。面对以下错误
错误:
“displayList Word”的正文不能是迭代器块,因为“void”不是迭代器接口类型。如果使用的是yield,则需要返回IEnumerable 额外资源 迭代器方法和get访问器 迭代器的声明必须满足以下要求: 返回类型必须为IEnumerable、IEnumerable、IEnumerator或IEnumerator 声明不能有任何in ref或out参数
具有Yield的方法应具有返回值,因为IEnumerablerReturn类型pf显示函数必须是字符串的可枚举函数,并且您应该迭代该返回值以正常工作。希望这对你有帮助。
IEnumerable<string> display(List<string> words) // display method implementation
{
foreach (string word in words)
{
if (word == "TamilSelvi") yield return word;
}
}
var result = display(names);
foreach (var name in result)
{
Console.WriteLine(name);
}