为什么类型推断逻辑会因对 TreeNodeCollection 的迭代而失败?

Why does the type-inferencing logic fails with an iteration over a TreeNodeCollection?

我对这种行为有点不解,

此代码编译正常:

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 是强类型的。是因为这个集合类型已经过时了吗?

谁能告诉我这种行为的技术原因?

since the TreeNodeCollection is strongly-typed

这里是TreeNodeCollectionclass的定义:

public class TreeNodeCollection : IList, ICollection, IEnumerable

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

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

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