简体   繁体   中英

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:

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. Why is it this way?

You get objects in foreach loop because FormCollection class implements non-generic IEnumerable interface (inherited from ReadOnlyCollectionBase). But it has indexer which returns Form .

Simply cast objects to Form type in loop:

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". Which FormCollection was inherited from ReadOnlyCollectionBase , then every instance in a collection were defined as an object. So can either cast it to a Form to use it, or just use Form in the foreach loop than using var .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM