var没有获得隐含值

时间:2014-12-02 12:33:12

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

我刚看到下面的代码:

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);
        }
    }
} 

如上所述出现错误:

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

2 个答案:

答案 0 :(得分:4)

不,它不会因为ControlCollection只实现非通用IEnumerable而不是通用IEnumerable<Control>所以当你枚举它而不提供类型时,你得到object < / p>

答案 1 :(得分:1)

使用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);
            }
        }
    }