gpt4 book ai didi

c# - 将函数作为参数传递给 Action

转载 作者:太空狗 更新时间:2023-10-30 01:20:16 47 4
gpt4 key购买 nike

我正在尝试将一个方法作为一个 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"};
}

我收到这个错误:

Overloaded method has some invalid arguments.

更新

这就是我设法解决这个问题的方法:

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

最佳答案

您不能将返回值的方法作为 Action 传递,因为 Action<T>必须带一个参数 T并且什么都不返回(即 void )。

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

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

关于c# - 将函数作为参数传递给 Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19592111/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com