[英]Access Application.OpenForms via foreach vs. index
I just stumpled over this issue and I'm curious why it is that way: If I access a form in the collection of Application.OpenForms
via index the compiler tells me it is a form: 我只是为这个问题而苦恼,我很好奇为什么会这样:如果我通过索引访问
Application.OpenForms
集合中的表单,编译器会告诉我这是一种表单:
var form = Application.OpenForms[0];
form.Name = "A new name";
This works perfectly fine. 这工作得很好。 But if I access it like this:
但是,如果我这样访问它:
foreach (var form in Application.OpenForms)
{
form.Name = "A new name";
}
The complier tells me form
is an object. 编译器告诉我
form
是一个对象。 Why is it this way? 为什么这样呢?
You get objects in foreach loop because FormCollection
class implements non-generic IEnumerable interface (inherited from ReadOnlyCollectionBase). 因为
FormCollection
类实现了非通用 IEnumerable接口(从ReadOnlyCollectionBase继承),所以您在foreach循环中获得了对象。 But it has indexer which returns Form
. 但是它具有返回
Form
索引器。
Simply cast objects to Form
type in loop: 只需在循环中将对象转换为
Form
类型即可:
foreach (Form form in Application.OpenForms)
{
form.Name = "A new name";
}
If you'll check Application.OpenForms
Property, its value was defined by "A FormCollection
containing all the currently open forms owned by this application". 如果要检查
Application.OpenForms
属性,则其值由“包含该应用程序当前所有打开的表单的FormCollection
”定义。 Which FormCollection
was inherited from ReadOnlyCollectionBase
, then every instance in a collection were defined as an object. 哪个
FormCollection
是从ReadOnlyCollectionBase
继承的,则集合中的每个实例都被定义为一个对象。 So can either cast it to a Form
to use it, or just use Form
in the foreach
loop than using var
. 因此,可以将其强制转换为
Form
以使用它,也可以仅在foreach
循环中使用Form
而不是使用var
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.