2012-11-26 31 views
3

我有以下函數來獲取所有類型的子控件。獲取控件的類型T的子控件

private IEnumerable<Control> GetControlsOfType(Control control, Type type) 
    { 
     var controls = control.Controls.Cast<Control>(); 

     return controls.SelectMany(ctrl => GetControlsOfType(ctrl, type)) 
            .Concat(controls) 
            .Where(c => c.GetType() == type); 
    } 

我想使用泛型類型參數進行轉換。

private IEnumerable<T> GetControlsOfType<T>(Control control) where T: Control 
    { 
     var controls = control.Controls.Cast<Control>(); 

     return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl)) 
            .Concat(controls) 
            .Where(c => c.GetType() == T); 
    } 

該代碼在.Concat上出錯。

錯誤6 'System.Collections.Generic.IEnumerable <T>' 不包含 定義爲 '的毗連' 和最好的擴展方法過載 「System.Linq.Queryable.Concat <TSource>(System.Linq的.IQueryable <TSource>, System.Collections.Generic.IEnumerable <TSource>)」有一些無效 參數

如何解決這個問題?

回答

3

嘗試增加.OfType<Control>()GetControlsOfType<T>(ctrl)和,而不是你Where

所以,你的代碼讀取:

return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl).OfType<Control>()) 
            .Concat(controls) 
            .OfType<T>(); 
+0

他要返回的IEnumerable'' - 不會在返回的IEnumerable''? –

+0

@JonB事實上,我更新到修復 –

+0

'GetControlsOfType (ctrl)'已經有'IEnumerable '類型。爲什麼在這裏需要'OfType ()'? – ca9163d9