我创建了一个可以通过字符串代码执行方法的类(这实际上是我想要的,因为(已经存在的)数据库包含这些代码。但是我希望它在添加更多数据库记录时更具可扩展性。现在我们必须为每个代码创建一个方法,但是我想使用一个接口和一个可以在不编辑这个类的情况下创建的类。你们有什么建议吗?
public class SpecificAction
{
public ActionToPerform ActionToPerform { get; private set; }
public string Action { get { return ActionToPerform.Action.Code; } }
public SpecificAction(ActionToPerform actionToPerform)
{
ActionToPerform = actionToPerform;
}
public dynamic Execute(object[] parametersArray = null)
{
Type type = typeof (SpecificAction);
MethodInfo methodInfo = type.GetMethod(Action);
dynamic result = null;
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
result = methodInfo.Invoke(this, parameters.Length == 0 ? null : parametersArray);
}
return result != null && result;
}
//"Restart" is one of the codes in the database
public bool Restart()
{
throw new NotImplementedException();
}
//"AddToEventLog" is one of the codes in the database
public bool AddToEventLog()
{
if (!EventLog.SourceExists("Actions"))
{
EventLog.CreateEventSource("Actions", "Application");
}
EventLog.WriteEntry("Actions", Action + "is executed", EventLogEntryType.Warning);
return true;
}
//"SendEmail" is one of the codes in the database
public bool SendEmail()
{
throw new NotImplementedException();
}
}
我这样称呼它并且它有效:
bool isPerformed = false;
var action = new SpecificAction(actionToPerform);
isPerformed = action.Execute();
但是,我会发现为每个可能的操作实现一个类并在其中动态执行一个方法会更好,这对于一些现有的模式是否可行,你能给我一个例子吗,因为我已经尝试了很多?