4

我试图将一个方法作为一个动作传递,但似乎铸造不是每个人说的。

这就是我的做法:

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

1 回答 1

5

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

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

Action empBasicAction = () => GetEmployeeBasicDetails(0);
于 2013-10-25T14:13:13.913 回答