最近一直在思考扩展方法的应用,与这篇文章中的想法一接合,可将代码进一步精简,并可增强可读性。
先看代码(仅用了三个分号):
static class Program

{
/**//// <summary>
/// 先执行命令,再返回自身
/// </summary>
public static T Do<T>(this T t, Action<T> action)
{
action(t);
return t;
}
static void Main(string[] args)
{
new Form()
.Do(f => f.Tag = new Random())
.Do(f => f.Controls.Add(new Label
{ AutoSize = true }))
.Do(f => f.Controls.Add(
new Button
{ Text = "start", Top = 50 }
.Do(button => button.Click += (sender, e) => button
.Do(_button => _button.Text = (_button.Text == "stop") ? "start" : "stop")
.Do(_b =>
{
while (f.Controls[1].Text == "stop" &&
(f.Controls[0] as Label)
.Do(
l => l.Text =
string.Join(" - ",
new string[33]
.Select((i, j) => (j + 1).ToString("d2"))
.OrderBy(i => (f.Tag as Random).Next(33))
.Take(7)
.OrderBy(i => i)
.ToArray()
)
+ " = " + (f.Tag as Random).Next(1, 17)
)
.Do(l => Application.DoEvents())
!= null
)
{ }
}
)
)//button.AddReturn、
)// AddControl(B=new Button)
)
.ShowDialog();
}
}
首先,看看这个扩展方法:
1
/**/
/// <summary>
2
/// 先执行命令,再返回自身
3
/// </summary>
4
public
static
T Do
<
T
>
(
this
T t, Action
<
T
>
action)
5
{
6
action(t);
7
return t;
8
}
这个方法先让t做一件事action,然后返回自身,通过这个扩展可以把很多代码串起来,如:
/**/
/// <summary>2
/// 先执行命令,再返回自身3
/// </summary>
4
public
static
T Do
<
T
>
(
this
T t, Action
<
T
>
action)5

{6
action(t);7
return t;8
}
1
private static void DoExample()2

{3
//常规代码4
Form form = new Form();5
form.Text = "Text";6
form.TopMost = true;7
form.WindowState = FormWindowState.Maximized;8
form.Tag = "Tag";9
form.ShowDialog();10
//精简代码11
new Form()12
.Do(f => f.Text = "Text")13
.Do(f => f.TopMost = true)14
.Do(f => f.WindowState = FormWindowState.Maximized)15
.Do(f => f.Tag = "Tag")16
.ShowDialog();17
}
Do也可以夹杂上其它代码,但这样会影响代码清晰,如下:
1
private static void DoExample_Bad()2

{3
new Form()4
.Do(f => Console.WriteLine("ABC"))5
.Do(f => Application.DoEvents())6
.ShowDialog();7
}
明白了Do扩展 ,再来看看前面的代码,先去除一部分,看看整体结构:
static void Main(string[] args)
{
new Form()
.Do(f => f.Tag = new Random())
.Do(f => f.Controls.Add(new Label { AutoSize = true }))
.Do(f => f.Controls.Add(new Button
).ShowDialog();
}
1

new Button
{ Text = "start", Top = 50 } 2
.Do(button => button.Click += (sender, e) => 3
button 4
.Do(_button => _button.Text = (_button.Text == "stop") ? "start" : "stop")5
.Do(_b =>生成并显示)6
)
1
while
(f.Controls[
1
].Text
==
"
stop
"
&&
2
(f.Controls[
0
]
as
Label).Do(生成并显示).Do(l
=>
Application.DoEvents())
!=
null
//
条件二
3
)
4
{}
条件二永远为真 ,加在这里为了节省分号。条件二Do里面的 生成并显示如下:
while
(f.Controls[
1
].Text
==
"
stop
"
&&
2
(f.Controls[
0
]
as
Label).Do(生成并显示).Do(l
=>
Application.DoEvents())
!=
null
//
条件二
3
)4

{}
1
l => l.Text = 2
string.Join(" - ",3
new string[33]4
.Select((i, j) => (j + 1).ToString("d2"))5
.OrderBy(i => (f.Tag as Random).Next(33))6
.Take(7)7
.OrderBy(i => i)8
.ToArray()9
)10
+ " = " + (f.Tag as Random).Next(1, 17)
使用Select((i,j)=>...)代替原文中Tag作为变量,也大大简化清晰了代码。
其它不多说了。
这篇文章主要目的是介绍扩展方法的一个应用:简化,清晰代码!
本文介绍了一种利用C#扩展方法精简代码的方法,通过一个实际案例展示了如何使用自定义扩展方法来串联多个操作,使得代码更加简洁易读。
2407

被折叠的 条评论
为什么被折叠?



