fai*_*gir 4 c# delegates action
我试图通过一个方法作为一个动作,但似乎不是每说一次。
这就是我的做法:
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]();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我作为参数传递的函数:
public object GetEmployeeBasicDetails(int employeeID)
{
return new { First_Name = "Mark", Middle_Initial = "W.", Last_Name = "Rooney"};
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
重载方法有一些无效参数。
更新
这就是我设法解决这个问题的方法:
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]();
}
}
Run Code Online (Sandbox Code Playgroud)
您不能将返回值的方法作为 传递Action,因为Action<T>必须接受一个参数T并且不返回任何内容(即void)。
您可以通过传递一个调用您的方法并忽略其输出的 lambda 来解决此问题:
Action empBasicAction = () => GetEmployeeBasicDetails(0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7555 次 |
| 最近记录: |