将函数作为参数传递给Action

时间:2013-10-25 14:08:40

标签: 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]();
    }
}

这是我作为参数传递的函数:

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]();
    }
}

1 个答案:

答案 0 :(得分:4)

您无法将值返回方法作为Action传递,因为Action<T>必须使用参数T并且不返回任何内容(即void)。

您可以通过传递调用方法的lambda并忽略其输出来解决此问题:

Action empBasicAction = () => GetEmployeeBasicDetails(0);