C# Can';在方法中传递func参数

C# Can';在方法中传递func参数,c#,C#,我正在尝试将Func传递给此方法。不过,我一直收到“method()”的语法错误。它说它需要两个有意义的参数,但是我如何将其传递给方法呢?我把它们分配为T1和T2 我怎样才能让这个回复也成为回复呢 我调用它的方式(我想要用来调用该方法的func) 我做错了什么 public TResponse ExecuteAndLog<T1, T2,TResponse>(Guid id, string Name, Func<T1, T2, TResponse> method) wher

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

我怎样才能让这个回复也成为回复呢

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

我做错了什么

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;
    }
}
public treponse ExecuteAndLog(Guid id、字符串名称、Func方法),其中treponse:class
{
尝试
{
日志(id、名称);
t响应x=方法();
日志(id、名称);
}
捕获(例外情况除外)
{
日志(id、名称);
投
}
}

如果
方法
应接收两个参数,则需要传递它们:

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;
    }
}
public treponse ExecuteAndLog(Guid id、字符串名称、Func方法、T1 arg1、T2 arg2),其中treponse:class
{
尝试
{
日志(id、名称);
t响应x=方法(arg1,arg2);
日志(id、名称);
返回x;
}
捕获(例外情况除外)
{
日志(id、名称);
投
}
}

我猜你真的想要这个

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;
    }
}
这样,您只需要一个ExecuteAndLog原型。如果在
Func
中包含输入(如您在示例中所做的),则必须传递参数,并且每个可能的服务调用签名都需要不同版本的ExecuteAndLog


注意:无论何时以这种方式使用lambda表达式,都要小心。

投票将其作为输入错误关闭,因为您只是试图调用一个没有所需数量的参数的方法。这很有意义!我把方法签名的格式弄错了,弄糊涂了。谢谢。我现在如何使用_service.Count(fileDate(DateTime),cycle int)调用这个函数?@magna_nz您可以使用
ExecuteAndLog(someGuid,someString,_service.Count,fileDate,cycle)调用它。
我不知道为什么我从一开始就没有想到这个方法。。。我只需要添加一个
返回x所以这是可以编译的
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));