首页 > 代码库 > BaseCommand

BaseCommand

 

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

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