【问题标题】:var not getting implicit valuevar 没有得到隐含值
【发布时间】:2014-12-02 12:33:12
【问题描述】:

我刚刚看到下面的代码:

public void ListControls(ControlCollection controls, List<Control> controlsFound)
{
    foreach (var control in controls)
    {
        if (control is IAttributeAccessor)
        {
            controlsFound.Add(control); //Error (Invalid argument to Add method)
            ListControls(control.Controls, controlsFound);
        }
    }
} 

上面报错:

如果我将foreach 中的var 更改为Control,那么它可以工作。原因是 Add 方法期望 Control 作为参数。但我认为 var 应该已经被 Control 隐式替换了,对吧?

【问题讨论】:

  • ControlCollection 没有实现IEnumerable&lt;Control&gt;

标签: c# asp.net var anonymous-types


【解决方案1】:

不,不是因为ControlCollection 只实现了非泛型IEnumerable 而不是泛型IEnumerable&lt;Control&gt;,所以当你在不提供类型的情况下枚举它时,你会得到object

【讨论】:

  • 既然是ControlCollection,那么它一定有Control的集合,编译器应该知道,为什么不是这样?
  • @Imad 编译器知道一个集合包含T 类型的项目,如果该集合实现了IEnumerable&lt;T&gt;ControlCollection 没有实现那个接口,所以编译器不知道项目是什么类型。
  • 推断ControlCollection包含Control的实例,因为它的名字。但是编译器怎么知道呢?
【解决方案2】:

使用 LINQ 即可:

public void ListControls(ControlCollection controls, List<Control> controlsFound)
    {
        foreach (var control in controls.OfType<Control>())
        {
            if (control is IAttributeAccessor)
            {
                controlsFound.Add(control); //Error (Invalid argument to Add method)
                ListControls(control.Controls, controlsFound);
            }
        }
    } 

【讨论】:

猜你喜欢
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2010-10-16
  • 2016-06-27
相关资源
最近更新 更多