Domanda

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 and DispatchB return a OrderResult object. I'm calling it like this

Order x = GetOrder();
OrderResult myResult = GetDispatcherForOrder(x);

And i get this error

Cannot implicitly convert type 'System.Func<Order, OrderResult>' to 'OrderResult'

How can i get the OrderResult?

È stato utile?

Soluzione

For when you must have a delegate (nothing in your code tells me that you do):

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);

For when you just need to get 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);

Altri suggerimenti

That is because your're trying to assign a delegate to a OrderResult object. I think you may wanted to write:

Func<Order, OrderResult> myResult = GetDispatcherForOrder(x);
private Func<Order, OrderResult> GetDispatcherForOrder(Order order)

Is a method that returns a delegate. But based on your example usage:

Order x = GetOrder();
OrderResult myResult = GetDispatcherForOrder(x);

You probably want something like this:

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");
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top