using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Windows.Input;
namespace FWindSoft.MVVM
{
///
/// 泛型CommandAdapterFactory类
///
///
internal static class CommandAdapterFactory where T : class
{
private static readonly Type m_Type;
///
/// 创建命令适配器(获取Execute方法和CanExecute方法为创建ICommand接口实例准备)
///
///
///
public static object Create(object sender)
{
CommandAdapter inst = (CommandAdapter) m_Type.GetConstructor(new Type[] {}).Invoke(new object[] {});
Type thisType = typeof (T);
MethodInfo[] methods = thisType.GetMethods();
foreach (MethodInfo methodItem in methods)
{
CommandAttribute[] attrs =
methodItem.GetCustomAttributes(typeof (CommandAttribute), true) as CommandAttribute[];
if ((attrs != null) && (attrs.Length != 0))
{
string methodName = methodItem.Name;
string canDoMethodName = "Can" + methodName;
bool hasCanDoMethod = (from method in methods
where method.Name == canDoMethodName
select method).FirstOrDefault() != null;
#region 初始化命令
BaseCommand cmd = new BaseCommand(
(x) =>
{
CommandEventArgs eargs = new CommandEventArgs(inst,
new CommandInfo() { CommandName = methodName });
inst.DoBeforeCommand(eargs);
try
{
try
{
MethodInfo miLocal = thisType.GetMethod(methodName);
ParameterInfo[] pi = miLocal.GetParameters();
if (pi.Length == 0)
{
thisType.InvokeMember(methodName, BindingFlags.Public, null, sender,
new object[] { });
}
else if (pi.Length == 1)
{
thisType.InvokeMember(methodName,
BindingFlags.InvokeMethod, null,
sender, new object[] { x });
}
}
catch
{
throw;
}
}
finally
{
inst.DoAfterCommand(eargs);
}
}, hasCanDoMethod
? (Predicate