using System; using System.Collections.Generic; using System.Linq;
namespaceSystem.Windows.Forms { publicstaticclassListBoxExtension { ///<summary> /// 获取 ListBox.Items 中的数据构成的集合 ///</summary> ///<typeparam name="T">ListBox.Items中储存的数据的类型</typeparam> ///<param name="listbox">ListBox对象</param> ///<returns></returns> publicstaticList<T> GetItems<T>(this ListBox listbox) where T : class { var items = newobject[listbox.Items.Count]; listbox.Items.CopyTo(items, 0);
var current = items.Select(i => i as T).Where(i => i != null).ToList(); if (listbox.Items.Count != current.Count) thrownew Exception($"并非所有元素都为{typeof(T).Name}类型");