private Func<Order, OrderResult> GetDispatcherForOrder(Order order)
{
switch (order.Type)
{
case "A":
return dispatcher => DispatchA(order.Id, order.Info, ...);
case "B":
return dispatcher => DispatchB(order.Id, order.Info, ...);
default:
throw new ArgumentOutOfRangeException("order.Type");
}
}
DispatchA和DispatchB返回一个OrderResult对象。 我这样称呼它
Order x = GetOrder();
OrderResult myResult = GetDispatcherForOrder(x);
我得到了这个错误
Cannot implicitly convert type 'System.Func<Order, OrderResult>' to 'OrderResult'
我如何获得OrderResult?
答案 0 :(得分:2)
当你必须有一个代表时(代码中没有任何内容告诉我你这样做):
private Func<Order, OrderResult> GetDispatcherForOrder(Order order)
{
switch (order.Type)
{
case "A":
return dispatcher => DispatchA(order.Id, order.Info, ...);
case "B":
return dispatcher => DispatchB(order.Id, order.Info, ...);
default:
throw new ArgumentOutOfRangeException("order.Type");
}
}
Order x = GetOrder();
Func<Order, OrderResult> myFunction = GetDispatcherForOrder;
OrderResult myResult = myFunction(x);
当你需要获得OrderResult的时候:
private OrderResult GetDispatcherForOrder(Order order)
{
switch (order.Type)
{
case "A":
return DispatchA(order.Id, order.Info, ...);
case "B":
return DispatchB(order.Id, order.Info, ...);
default:
throw new ArgumentOutOfRangeException("order.Type");
}
}
Order x = GetOrder();
OrderResult myResult = GetDispatcherForOrder(x);
答案 1 :(得分:0)
这是因为您尝试将委托分配给OrderResult
对象。我想你可能想写:
Func<Order, OrderResult> myResult = GetDispatcherForOrder(x);
答案 2 :(得分:0)
private Func<Order, OrderResult> GetDispatcherForOrder(Order order)
是一个返回委托的方法。但根据您的示例用法:
Order x = GetOrder();
OrderResult myResult = GetDispatcherForOrder(x);
你可能想要这样的东西:
private OrderResult GetDispatcherForOrder(Order order)
{
switch (order.Type)
{
case "A":
return DispatchA(order.Id, order.Info, ...);
case "B":
return DispatchB(order.Id, order.Info, ...);
default:
throw new ArgumentOutOfRangeException("order.Type");
}
}