为什么一个对象没有与VAR一个foreach stongly类型? [英] Why is an object not stongly typed in a foreach with var?

查看:286
本文介绍了为什么一个对象没有与VAR一个foreach stongly类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写以下

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)
    {

    }
}

我可以用方便地访问它们 item.Controls

i could easily access them using item.Controls

所以我想知道的为什么我真的需要定义/施放这些项目为的TabPage ,不应该编译/ intellasense弄清楚里面为每个项目 this.tabControl1.TabPages 实际上是一个的TabPage

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 ?

推荐答案

由于的 TabControl.TabPages 返回的 TabPageCollection 没有实现强类型的IEnumerable< T> ,但它返回一个对象的非通用的IEnumerable 接口

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.

所以,如果你提供的的foreach 将被铸造隐含的类型。如果不提供类型它的类型是对象和以后需要投放。

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.

读< A HREF =http://msdn.microsoft.com/en-us/library/aa664754%28v=vs.71%29.aspx相对=nofollow> C#语言规范,8.8.4 获得更多的信息。

Read C# language spec, 8.8.4 for more informations.

您也可以使用LINQ的扩展方法 Enumerable.Cast

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

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

它的方便,特别是如果你想使用Linq:

It's handy especially if you want use Linq:

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

这篇关于为什么一个对象没有与VAR一个foreach stongly类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆