C# Cast
时间:2022-03-17 22:29
窗体控件中是有个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<T>。以下代码假定 listBox 数据绑定在一个Employee的集合上:
- int count = listBox.Items.Cast<Employee>().Count();
- bool b = listBox.Items.Cast<Employee>().Any(e => e.FirstName == "Bob");
同样C# Cast<T>可以用在ComboBox、DataGridView、TreeNode上:
- //ComboBox
- var v1 = comboBox.Items.Cast<People>();
- //DataGridView
- var v2 = dataGridView.SelectedRows.Cast<DataGridViewRow>();
- var v3 = dataGridView.SelectedColumns.Cast<DataGridViewColumn>();
- var v4 = dataGridView.SelectedCells.Cast<DataGridViewCell>();
- //TreeNode
- var v5 = treeNode.Nodes.Cast<TreeNode>();
这几个应用中应该第 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<T>,我们的代码很精简。Cast<T>甚至还可以用在所有控件的基类Control上,它的Controls属性也是非泛型的!
- //Control
- var v6 = control.Controls.Cast<Control>();
看来C# Cast<T>好像是为 Control 准备,Control 类和Control 的派生类多处使用了非泛型。可现在都用vs2008(甚至vs2010)了,那为什么WinForm的窗体控件还用非泛型,太落后了吧!!!确实如此,WinForm对泛型控件(Control)的支持上存在很大问题。虽然可以定义泛型控件,也可以使用,可以运行。但会有很多麻烦的,比如窗体设计器没法显示...那只好使用非泛型的了,好在我们有C# Cast<T>!
本类排行
- 1terminate called after throwing an instance of 'std::cad_alloc' what():std::bad_alloc
- 2动态 WebApi 引擎使用教程(3行代码完成动态 WebApi 构建)
- 3windows 查看文件的md5/sha1/sha256
- 4打造一个window桌面应用:在线聊天对话机器人
- 5git windows下换行符问题 LF与CRLF转换
- 6[Linux]Windows远程CENTOS7桌面
- 7FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。
- 8K8S--可视化界面Kubernetes Dashboard(API Server方式)
- 9搜索引擎sphinx的windows安装和使用
- 10Redis安装成windows服务