【问题标题】:Why does the type-inferencing logic fails with an iteration over a TreeNodeCollection?为什么在 TreeNodeCollection 上进行迭代时类型推断逻辑会失败?
【发布时间】:2017-11-09 12:48:19
【问题描述】:

我对这种行为有点疑惑,

这段代码编译得很好:

private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( TreeNode treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...     
       }
   }
}

但是下面会产生一个编译错误,说'object' does not contain a definition for 'Tag'

private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( var treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...     
       }
   }
}

在这种情况下,类型推断逻辑返回 Object 作为迭代器的结果类型,但我不清楚为什么,因为 TreeNodeCollection 是强类型的。是不是因为这个收藏类型已经过时了?

有人能告诉我这种行为的技术原因吗?

【问题讨论】:

    标签: .net winforms visual-studio-2013 type-inference c#-5.0


    【解决方案1】:

    因为TreeNodeCollection 是强类型的

    这里是TreeNodeCollection类的定义:

    public class TreeNodeCollection : IList, ICollection, IEnumerable
    

    如您所见,它不是强类型的,因为它实现了非通用的IEnumerable 接口而不是IEnumerable<TreeNode>。所以类型推断有效,只是从IEnumerable.Current 推断的类型是object

    这基本上适用于所有 WinForms 集合。尽管它们中的大多数都提供了强类型索引器,但它们都实现了非通用的IEnumerable 接口。

    为什么?因为它们是在泛型(因此IEnumerable<T> 接口)不存在时创建的。而且永远不会更新。

    【讨论】:

    • 确实,集合的强类型“外观”让我相信它在某种程度上是强类型的。感谢您的洞察力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多