博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
累加器配上委托也可以很吊
阅读量:6867 次
发布时间:2019-06-26

本文共 1815 字,大约阅读时间需要 6 分钟。

我们知道在ASP.NET MVC中,在Action方法上应用ActionFilter过滤法时,它的执行流程如下图:

这个功能看起来很一般麽,可是实现功能的代码吊炸天(嘿嘿,要班门弄斧了,大神绕行吧!),卡忙北鼻...

由于在ASP.NET MVC中其功能涉及的代码太多,看起来太乱,下面就通过一个例子重点来介绍下这段吊爆的代码!

例子的环境是这样的:

1、有这么一个接口IFilterFunction,其中定义了两个方法!

1
2
3
4
5
6
public 
interface 
IFilterFunction
{
    
void 
Before();
 
    
void 
After();
}

2、一个方法!

1
2
3
4
5
public 
string 
ActionMethed()
{
    
Console.WriteLine(
"Action方法内容"
);
    
return 
"Action"
;
}

需求来了,为了在执行ActionMethod方法的前后进行一些操作,要求实现功能:先执行所有实现了IFilterFunction接口的所有类的Before方法,再执行ActionMethed方法,然后再执行所有实现了IFilterFunction接口的所有类的After方法!(目的是在执行ActionMethod方法的前后进行一些操作)

 对于这么一个需求,首先想到可以这么实现:

小吊实现:

 
实现IFilterFunction接口的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public 
string 
Start()
{
    
FilterOne filterOne = 
new 
FilterOne();
    
FilterTwo filterTwo = 
new 
FilterTwo();
    
FilterThree filterThree = 
new 
FilterThree();
 
    
filterThree.Before();
    
filterTwo.Before();
    
filterOne.Before();
 
    
string 
str = ActionMethed();
 
    
filterOne.After();
    
filterTwo.After();
    
filterThree.After();
 
    
return 
str;
}

虽然说可以实现,但是这么做有点太小儿科了,说好的吊爆呢?

来咯......

大吊实现:

 
实现接口IFilterFunction的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public 
string 
Start()
{
    
Func<
string
> continuation = () => ActionMethed();
 
    
List<IFilterFunction> lists = 
new 
List<IFilterFunction>();
    
lists.Add(
new 
FilterOne());
    
lists.Add(
new 
FilterTwo());
    
lists.Add(
new 
FilterThree());
    
//就是它
    
Func<
string
> p = lists.Aggregate(continuation, (newcontinuation, filter) => () => Do(newcontinuation, filter));
    
return 
p();
}
 
public 
string 
Do(Func<
string
> continuation, IFilterFunction filter)
{
    
filter.Before();
 
    
string 
str = continuation();
 
    
filter.After();
 
    
return 
str;
}

执行结果为:

 

 

 

 

 

没错,就是这么牛逼,利用累加器来一层一层的包装委托,之后执行委托,再一层一层的去执行。其过程如图:

ASP.NET MVC也就是使用这种方式来完成对Action方法和ActionFilter过滤器的执行。即:利用累加器来包装委托!

朋友,你能写出这样的代码吗? 

 

本文转自武沛齐博客园博客,原文链接:http://www.cnblogs.com/wupeiqi/p/3601104.html,如需转载请自行联系原作者

你可能感兴趣的文章
gitlab备份与恢复
查看>>
运用mysql 中的source命令导入大的sql文件的解决方法
查看>>
CDH + phoenix+ zeppelin
查看>>
Cloudera与Hortonworks宣布合并创建全球领先的下一代数据平台
查看>>
JDBC Statement PreparedStatement CallableStatement
查看>>
Asynchronous Module Definition (AMD)
查看>>
javac java 命令行编译运行程序
查看>>
几个重要的Linux系统内核文件介绍
查看>>
jquery ajax “Uncaught TypeError: Illegal invocation”
查看>>
Android 农历和节气相关工具类(记录)
查看>>
php字符串处理函数大全
查看>>
redis应用场景
查看>>
页面加载自动定位到显示位置
查看>>
JTree实现文件树
查看>>
FMDB详解
查看>>
F12浏览器调试模式页面刷新network日志刷新消失的解决办法
查看>>
DiskGroup resource are not running on nodes. Database instance may not come up on these nodes
查看>>
nginx+keepalived实现集群配置
查看>>
maven常用命令整理
查看>>
2.6 yum如何下载rpm包到本地
查看>>