.net cf 1.0->.net cf 2.0->.net cf3.5
随着cf版本的升级,我们不断的在使用着cf提供的新功能。有没有想过如何改善代码质量?不仅使得代码看起来更清晰呢?
随着C#3.0的推出,相信泛型已成为大家耳熟能详的名词。在今后的项目中,我们如不尝试使用它来创建控件吧。
原先,我们在Form上添加一个控件,使用如下方法:
2 clickButton.Name = " button " ;
3 clickButton.Text = " Click Me " ;
4 clickButton.Location = new Point( 100 , 200 );
5 clickButton.Font = this .Font;
6 this .Controls.Add(clickButton);
我们使用范型来改善下:
2 {
3 InitializeComponent();
4
5 // Create button and add it to the Form's controls collection
6 Button clickButton = this .AddControl < Button > (c => new Button()
7 {
8 Name = " button " ,
9 Text = " Click Me " ,
10 Location = new Point( 100 , 200 ),
11 Font = c.Font
12 });
13 // Hook up into the click event
14 clickButton.Click += new EventHandler(clickButton_Click);
15 // Create label
16 this .AddControl < Label > (c => new Label()
17 {
18 Name = " labelHello " ,
19 Location = new Point( 100 , 240 )
20 });
21 }
22
23 void clickButton_Click( object sender, EventArgs e)
24 {
25 // Assign the value to the Text property of the label
26 this .GetControl < Label > ( " labelHello " ).Text = " Hello world. " ;
27 }
2 {
3 public static T AddControl < T > ( this Control parent,Func < Control, T > build)
4 {
5 T control = build(parent);
6 parent.Controls.Add(control as Control);
7 return control;
8 }
9
10 public static Control GetControl( this Control parent, string name)
11 {
12 return parent.Controls.OfType < Control > ().SingleOrDefault(c => c.Name == name);
13 }
14
15 public static T GetControl < T > ( this Control parent, string name) where T : Control
16 {
17 return parent.Controls.OfType < Control > ().SingleOrDefault(c => c.Name == name) as T;
18 }
19 }
这样代码看起来更清晰,虽然多做了一些额外的工作,但使得我们的工作更有效了。
优点:代码更清晰,适用于动态添加控件。
缺点:代码与Design无法兼容阿,不利于UI调试。不适用于非动态添加控件,毕竟在WM系统中通过.net cf来动态创建很多控件是很消耗资源的。
这篇文章参考自:Alex Yakhnin的《Generic control creation. 》
文章中的代码在WM中有一个地方需修改,在ControlExtension类中,parent.Controls集合对象不支持直接用名字来查找控件。故此需要做一些小的调整。
运行环境:VS2008 + WM6.0 + .net cf3.5
Author:AppleSeeker(冯峰)
Date:2009-01-23
文章导读:移动开发索引贴