• 概述C# Cast()


        窗体控件中是有个List控件(ASP.Net)和一个ListView控件(WinForm)。

        就以ListView为例子吧,ListView控件可以包含很多项,也可以说是一个集合,就让我们来看看它的Items属性吧!

    1. public class ListView : Control{  
    2. public ListView.ListViewItemCollection Items { get; }  
    3. public class ListViewItemCollection : IList, ICollection, IEnumerable {    
    4. }  

        ListView的Items类型是ListView.ListViewItemCollection,这个ListViewItemCollection实现了IEnumerable。ListView.Items正是一个非泛型的集合,因此可以应用Cast<T>。以下代码假定 listBox 数据绑定在一个Employee的集合上:

    1. int count = listBox.Items.Cast<Employee>().Count();  
    2. bool b = listBox.Items.Cast<Employee>().Any(e => e.FirstName == "Bob"); 

        同样C# Cast<T>可以用在ComboBox、DataGridView、TreeNode上:

    1. //ComboBox  
    2. var v1 = comboBox.Items.Cast<People>();  
    3. //DataGridView  
    4. var v2 = dataGridView.SelectedRows.Cast<DataGridViewRow>();  
    5. var v3 = dataGridView.SelectedColumns.Cast<DataGridViewColumn>();  
    6. var v4 = dataGridView.SelectedCells.Cast<DataGridViewCell>();  
    7. //TreeNode  
    8. var v5 = treeNode.Nodes.Cast<TreeNode>(); 

        这几个应用中应该第 4 行的应用最多,获取选中行是DataGridView使用最频繁的操作之一。试看下面代码:

    1. //计算平均年龄  
    2. int age = dataGridView.SelectedRows.
      Cast<Employee>().Average(p=>p.Age);  
    3. //统计所在城市  
    4. string[] cities = dataGridView.SelectedRows.
      Cast<Employee>().Select(p => p.City).Distinct(); 

        用了C# Cast<T>,我们的代码很精简。Cast<T>甚至还可以用在所有控件的基类Control上,它的Controls属性也是非泛型的!

    1. //Control  
    2. var v6 = control.Controls.Cast<Control>(); 

        看来C# Cast<T>好像是为 Control 准备,Control 类和Control 的派生类多处使用了非泛型。可现在都用vs2008(甚至vs2010)了,那为什么WinForm的窗体控件还用非泛型,太落后了吧!!!确实如此,WinForm对泛型控件(Control)的支持上存在很大问题。虽然可以定义泛型控件,也可以使用,可以运行。但会有很多麻烦的,比如窗体设计器没法显示...那只好使用非泛型的了,好在我们有C# Cast<T>!

    乌龟才背着房子过一辈子
  • 相关阅读:
    mysql零碎问题合集
    mysql 纵表转横表 需要用join不能直接where连接
    eclipse导出可执行jar包 报main function not found错误
    shell脚本将mysql查询结果制作成csv格式
    linux shell中把句子中的单词提取作为变量值 主要是使用了数组
    linux下文件字符编码转换
    Banner使用
    recyclerview的博客网址需要的权限
    okhttp权限
    Okhttp代码
  • 原文地址:https://www.cnblogs.com/Yellowshorts/p/2848816.html
Copyright © 2020-2023  润新知