【问题标题】:Can't pass func arguments within method [closed]无法在方法中传递 func 参数[关闭]
【发布时间】:2019-01-07 06:40:42
【问题描述】:

我正在尝试将Func<TResponse, T1, T2> 传递给此方法。不过,我不断收到“method()”的语法错误。它说它需要两个有意义的参数,但是我如何将它传递给方法?我已将它们分配为 T1 和 T2。

我怎样才能让它也返回 TResponse?

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

_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;
    }
}

【问题讨论】:

  • 投票关闭这是一个错字,因为您只是想调用一个没有所需参数数量的方法。

标签: c#


【解决方案1】:

我猜你真的想要这个....

public TResponse ExecuteAndLog<TResponse>(Guid id, string Name, Func<TResponse> method) where TResponse : class
{
    try
    {
        Log(id, Name);
        TResponse x = method();
        Log(id, Name);
    }
    catch (Exception ex)
    {
        Log(id, Name);
        throw;
    }
}

你会用它来称呼它

var response = ExecuteAndLog(someGuid, someName, () => _service.Count(fileDate, cycle));

这样你只需要一个 ExecuteAndLog 原型。如果您在 Func 中包含输入(如您在示例中所做的那样),则必须传递参数,并且您需要为每个可能的服务调用签名使用不同版本的 ExecuteAndLog。

注意:每当您以这种方式使用 lambda 表达式时,请注意closures

【讨论】:

  • 我不知道为什么我从一开始就没有想到这种方式......我只想添加一个return x; 这样编译虽然
【解决方案2】:

如果method应该接收两个参数,你需要传递它们:

public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method, T1 arg1, T2 arg2) where TResponse : class
{
    try
    {
        Log(id, Name);
        TResponse x = method(arg1, arg2);
        Log(id, Name);

        return x;
    }
    catch (Exception ex)
    {
        Log(id, Name);
        throw;
    }
}

【讨论】:

  • 这很有意义!我弄错了方法签名的格式并感到困惑。谢谢。
  • 我现在如何使用 _service.Count(fileDate (DateTime), cycle int)) 调用这个函数?
  • @magna_nz 你可以使用ExecuteAndLog(someGuid, someString, _service.Count, fileDate, cycle)来调用它
猜你喜欢
  • 1970-01-01
  • 2013-12-18
  • 2011-10-18
  • 2013-01-25
  • 2018-05-24
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多