无法在方法中传递 func 参数

我试图Func<TResponse, T1, T2>通过这个方法。不过,我一直收到“method()”的语法错误。它说它需要两个有意义的参数,但我如何将它传递给方法?我已将它们指定为 T1 和 T2。


我怎样才能让这个返回 TResponse 呢?


我调用它的方式(我想用来调用方法的 func)。


_service.Count(fileDate (DateTime), cycle int));

我在这里做错了什么?


public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method) where TResponse : class

{

    try

    {

        Log(id, Name);

        TResponse x = method();

        Log(id, Name);

    }

    catch (Exception ex)

    {

        Log(id, Name);

        throw;

    }

}


汪汪一只猫
浏览 250回答 2
2回答

侃侃尔雅

我猜你真的想要这个......public TResponse ExecuteAndLog<TResponse>(Guid id, string Name, Func<TResponse> method) where TResponse : class{&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; &nbsp; &nbsp; TResponse x = method();&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; }&nbsp; &nbsp; catch (Exception ex)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; &nbsp; &nbsp; throw;&nbsp; &nbsp; }}你会用var response = ExecuteAndLog(someGuid, someName, () => _service.Count(fileDate, cycle));这样你只需要一个 ExecuteAndLog 的原型。如果您将输入包含在Func(正如您在示例中所做的那样),则必须传递参数,并且对于每个可能的服务调用签名,您都需要不同版本的 ExecuteAndLog。

慕桂英546537

如果method应该接收两个参数,则需要传递它们:public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method, T1 arg1, T2 arg2) where TResponse : class{&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; &nbsp; &nbsp; TResponse x = method(arg1, arg2);&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; &nbsp; &nbsp; return x;&nbsp; &nbsp; }&nbsp; &nbsp; catch (Exception ex)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Log(id, Name);&nbsp; &nbsp; &nbsp; &nbsp; throw;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP