概述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>!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM