我试图将一个方法作为一个动作传递,但似乎铸造不是每个人说的。
这就是我的做法:
public class RequestHandler<T> where T : struct
{
public enum EmployeeRequests { BasicDetails, DependentsAndEmergencyContacts , MedicalHistory }
protected Dictionary<T, Action> handlers = new Dictionary<T, Action>();
protected EmployeeManagement empMgmnt = new EmployeeManagement();
public void InitializeHandler(int employeeID)
{
this.AddHandler(EmployeeRequests.BasicDetails, () => empMgmnt.GetEmployeeBasicDetails(0));
}
public void AddHandler(T caseValue, Action action)
{
handlers.Add(caseValue, action);
}
public void RemoveHandler(T caseValue)
{
handlers.Remove(caseValue);
}
public void ExecuteHandler(T actualValue)
{
ExecuteHandler(actualValue, Enumerable.Empty<T>());
}
public void ExecuteHandler(T actualValue, IEnumerable<T> ensureExistence)
{
foreach(var val in ensureExistence)
if (!handlers.ContainsKey(val))
throw new InvalidOperationException("The case " + val.ToString() + " is not handled.");
handlers[actualValue]();
}
}
这是我作为参数传递的函数:
public object GetEmployeeBasicDetails(int employeeID)
{
return new { First_Name = "Mark", Middle_Initial = "W.", Last_Name = "Rooney"};
}
我收到此错误:
重载的方法有一些无效的参数。
更新
这就是我设法解决这个问题的方法:
public static class RequestHandler
{
public enum EmployeeRequests { BasicDetails = 0, DependentsAndEmergencyContacts = 1 , MedicalHistory = 2 }
private static Dictionary<EmployeeRequests, Func<object>> handlers = new Dictionary<EmployeeRequests, Func<object>>();
public static void InitializeHandler(int employeeID)
{
Func<object> EmpBasicDetails = delegate { return EmployeeManagement.GetEmployeeBasicDetails(0); };
AddHandler(EmployeeRequests.BasicDetails, EmpBasicDetails);
}
private static void AddHandler(EmployeeRequests caseValue, Func<object> empBasicAction)
{
handlers.Add(caseValue, empBasicAction);
}
public static void RemoveHandler(int caseValue)
{
var value = (EmployeeRequests)Enum.Parse(typeof(EmployeeRequests), caseValue.ToString());
handlers.Remove(value);
}
public static object ExecuteHandler(int actualValue)
{
var request = (EmployeeRequests)Enum.Parse(typeof(EmployeeRequests), actualValue.ToString());
return handlers[(EmployeeRequests)request]();
}
}