码迷,mamicode.com
首页 > 其他好文 > 详细

BaseCommand

时间:2014-10-22 01:00:14      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:io   ar   for   sp   on   cti   ad   bs   ef   

 

近来想着把以前做的项目实现抽象处理一下,随便写了点东西,自己记一下吧。

public class BaseCommand<T>
{
public delegate void BeforeExecuteHandler(T sender);
public event BeforeExecuteHandler BefaultExecuteEvent;

public delegate void AfterExecuteHandler(T sender);
public event AfterExecuteHandler AfterExecuteEvent;

private readonly Func<T, bool> _execute;
private readonly Predicate<T> _canExecute;

// private readonly Func<T, CommandResult> _execute;

public BaseCommand(Func<T, bool> execute)
: this(execute, null)
{
}

public BaseCommand(Func<T, bool> execute, Predicate<T> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}

this._execute = execute;
this._canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return _canExecute == null ? true : this._canExecute((T)parameter);
}

public bool Execute(object parameter, Func<T, bool> preExecute)
{
if (!(parameter is T))
{
throw new InvalidCastException("parameter");
}

if (!CanExecute(parameter))
{
return false;
}

bool isPreExecuteFinish = false;

isPreExecuteFinish = preExecute == null ? true : preExecute((T)parameter);

if (isPreExecuteFinish)
{
return this._execute((T)parameter);
}
else
{
return false;
}
}

public bool Execute(object parameter, Action<T> preExecute)
{
if (!(parameter is T))
{
throw new InvalidCastException("parameter");
}

if (CanExecute(parameter))
{
preExecute((T)parameter);

return this._execute((T)parameter);
}
else
{
return false;
}
}

 

///

///以事件形式,实现执行前后的其它操作

///

public bool Execute(object parameter)
{
if (!(parameter is T))
{
throw new InvalidCastException("parameter");
}

if (CanExecute(parameter))
{
if (BefaultExecuteEvent != null)
{
BefaultExecuteEvent((T)parameter);
}

bool result = this._execute((T)parameter);

if (AfterExecuteEvent != null)
{
AfterExecuteEvent((T)parameter);
}

return result;
}
else
{
return false;
}
}

}

BaseCommand

标签:io   ar   for   sp   on   cti   ad   bs   ef   

原文地址:http://www.cnblogs.com/mx22/p/4041805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!