C#的Cast<T>怎么使用
这篇文章主要讲解了"C#的Cast
窗体控件中是有个List控件(ASP.Net)和一个ListView控件(WinForm)。
就以ListView为例子吧,ListView控件可以包含很多项,也可以说是一个集合,就让我们来看看它的Items属性吧!
public class ListView : Control{ public ListView.ListViewItemCollection Items { get; } public class ListViewItemCollection : IList, ICollection, IEnumerable { } }
ListView的Items类型是ListView.ListViewItemCollection,这个ListViewItemCollection实现了IEnumerable。ListView.Items正是一个非泛型的集合,因此可以应用Cast
int count = listBox.Items.Cast().Count(); bool b = listBox.Items.Cast ().Any(e => e.FirstName == "Bob");
同样C# Cast
//ComboBox var v1 = comboBox.Items.Cast(); //DataGridView var v2 = dataGridView.SelectedRows.Cast (); var v3 = dataGridView.SelectedColumns.Cast (); var v4 = dataGridView.SelectedCells.Cast (); //TreeNode var v5 = treeNode.Nodes.Cast ();
这几个应用中应该第 4 行的应用最多,获取选中行是DataGridView使用最频繁的操作之一。试看下面代码:
//计算平均年龄
int age = dataGridView.SelectedRows.
Cast<Employee>().Average(p=>p.Age);//统计所在城市
string[] cities = dataGridView.SelectedRows.
Cast<Employee>().Select(p => p.City).Distinct();
用了C# Cast
//Control var v6 = control.Controls.Cast();
感谢各位的阅读,以上就是"C#的Cast