我有一个控件列表(_controlList),从控件列表中我想得到从给定类派生的控件.所以我的代码看起来像这样.
List_controlList = new List (); public Control[] ControlsThatIsA(Type soughtType) { List result = new List (); foreach (Control control in _controlList) { // This would have been nice but doesn't compile ////////////// // if (control.GetType() is soughtType) { result.Add(control); } } return result.ToArray(); }
有什么想法吗.我没有传入Type,它可能是类的字符串名称
首先,我可能会使用泛型:
public T[] ControlsOfType() where T : Control { List result = new List (); foreach (Control control in _controlList) { if (control is T) { result.Add((T)control); } } return result.ToArray(); }
或者在.NET 3.5中:
return _controlList.OfType().ToArray();
如果你需要使用Type
,那么IsAssignableFrom
特别是你的朋友:
if(soughtType.IsAssignableFrom(control.GetType())) { //... }