我可以有一个返回 IEnumerator的方法吗? 并在 foreach 循环中使用它?
我需要设置表单上每个文本框的高度,其中一些文本框嵌套在其他控件中。 我想我可以做这样的事情:
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0)
{
// Recursively search for any TextBoxes within each child control
foreach (TextBox textBox in FindTextBoxes(control))
{
yield return textBox;
}
}
TextBox textBox2 = control as TextBox;
if (textBox2 != null)
{
yield return textBox2;
}
}
}
像这样使用它:
foreach(TextBox textBox in FindTextBoxes(this))
{
textBox.Height = height;
}
但是编译器当然会吐出它的虚拟值,因为 foreach 需要一个 IEnumerable 而不是 IEnumerator< /强>。
有没有一种方法可以做到这一点,而不必使用 GetEnumerator() 方法创建单独的类?
I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl)
{
foreach (Control control in rootControl.Controls)
{
if (control.Controls.Count > 0)
{
// Recursively search for any TextBoxes within each child control
foreach (TextBox textBox in FindTextBoxes(control))
{
yield return textBox;
}
}
TextBox textBox2 = control as TextBox;
if (textBox2 != null)
{
yield return textBox2;
}
}
}
Using it like this:
foreach(TextBox textBox in FindTextBoxes(this))
{
textBox.Height = height;
}
But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator.
Is there a way to do this without having to create a separate class with a GetEnumerator() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如编译器告诉您的那样,您需要将返回类型更改为 IEnumerable。 这就是yield return 语法的工作原理。
As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
只是为了澄清
对此的更改
应该是全部:-)
Just to clarify
Changes to
That should be all :-)
如果返回 IEnumerator,则每次调用该方法时它将是一个不同的枚举器对象(就像在每次迭代时重置枚举器一样)。 如果返回 IEnumerable,则 foreach 可以基于带有yield 语句的方法进行枚举。
If you return IEnumerator, it will be a different enumerator object each time call that method (acting as though you reset the enumerator on each iteration). If you return IEnumerable then a foreach can enumerate based on the method with the yield statement.
如果给定一个枚举器,并且需要在 for-each 循环中使用它,则可以使用以下内容来包装它:
toEnumerable
方法将接受任何 c# 或 vb 会将GetEnumerator
视为可接受的返回类型,并返回可在 <代码>foreach。 如果参数是IEnumerator<>
,则响应将为IEnumerable
,但对其调用GetEnumerator
一次可能会产生不良结果结果。If you are given an enumerator, and need to use it in a for-each loop, you could use the following to wrap it:
The
toEnumerable
method will accept anything that c# or vb would regard an acceptable return type fromGetEnumerator
, and return something that can be used inforeach
. If the parameter is anIEnumerator<>
the response will be anIEnumerable<T>
, though callingGetEnumerator
on it once will likely yield bad results.