Why is an object not stongly typed in a foreach with var?

徘徊边缘 提交于 2020-01-24 11:06:37

问题


i was writing the following

if(this.tabControl1.TabPages.Count != ImagesList.Count())
{
    foreach (var item in this.tabControl1.TabPages)
    {

    }
}

and i couldn't access the controls inside each item using item. But with a defining it's type like

if(this.tabControl1.TabPages.Count != ImagesList.Count())
{
    foreach (TabPage item in this.tabControl1.TabPages)
    {

    }
}

i could easily access them using item.Controls

so i was wondering why do i really need to define/cast those items as TabPage, shouldn't the compiler/intellasense figure it out as each item inside this.tabControl1.TabPages is actually a TabPage ?


回答1:


Because TabControl.TabPages returns a TabPageCollection which does not implement the strongly typed IEnumerable<T> but the non-generic IEnumerable interface which returns an object.

So if you provide the type in the foreach it will be casted implicitely. If you don't provide the type it's type is object and you need to cast it later.

Read C# language spec, 8.8.4 for more informations.

You could also use the Linq extension method Enumerable.Cast:

foreach (var item in this.tabControl1.TabPages.Cast<TabPage>())
{
    // item is TabPage
}

It's handy especially if you want use Linq:

var tabs =  this.tabControl1.TabPages.Cast<TabPage>()
     .Where(tp => tp.Name.StartsWith("MyTabPage"));



回答2:


Do you want to to this?

foreach (TabPage t in tabControl1.TabPages)
{
    foreach (Control c in t.Controls)
    {
        string a = c.Name;
    }
}


来源:https://stackoverflow.com/questions/19133692/why-is-an-object-not-stongly-typed-in-a-foreach-with-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!