c#将参数添加到Func

Alo*_*zo2 0 c# func

我有这些功能:

public List<int> GetInts(int someParam)
public List<int> GetMoreInts(int someParam, int anotherParam)
Run Code Online (Sandbox Code Playgroud)

我更改了这些函数的签名,以便它们获得一个额外的可选参数:

public List<int> GetInts(int someParam, int offset = 0)
public List<int> GetMoreInts(int someParam, int anotherParam, int offset = 0)
Run Code Online (Sandbox Code Playgroud)

现在,我想调用一个包装函数,它将使用附加的可选参数调用这些函数:

public List<int> Wrapper(Func<List<int>> queryFunc)
{
    var offset = 5;
    return queryFunc(offset);
}
Run Code Online (Sandbox Code Playgroud)

我将以这种方式调用包装器:

List<int> result = Wrapper(() => GetInts(0));
Run Code Online (Sandbox Code Playgroud)

我怎么能完成它?当我不知道Func指向的函数的签名时,如何向Func添加参数?

如果我想这样做的原因是相关的:

我有许多函数,具有不同的签名,查询不同的数据库表.其中一些查询的结果集太大,所以我想使用(MySQL)Limit函数:

'some mysql query'limit offset,batchsize

然后在包装函数中连接结果.所以我在一些函数中添加了额外的参数(offset,batchsize).我希望包装函数将这些参数添加到Func指向的函数中.

编辑: 我不明白投票的原因.

我有多个具有不同签名的函数来查询我的数据库.

问题是在某些情况下,结果集太大而且我得到超时异常.

因为结果集太大,我想得到一小块结果集,然后将它们全部连接到完整的结果集中.

例如:原始结果集大小为500K,导致超时.

我希望得到大小为1K,500倍的结果集.

这就是为什么我需要从Wrapper中控制偏移量,以便在每次迭代时,我可以发送偏移量,该偏移量在每次迭代后递增,作为原始函数的参数.

juh*_*arr 5

你只需要制作一个Func单一的int并返回List<int>.

public List<int> Wrapper(Func<int, List<int>> queryFunc)
{
    var offset = 5;
    return queryFunc(offset);
}
Run Code Online (Sandbox Code Playgroud)

然后你必须通过传入lambdas来使用它,你可以使用所需的参数调用你的其他函数并传入lambdas参数作为offset.

var result1 = Wrapper(o => GetInts(someParam, o));
var result2 = Wrapper(o => GetMoreInts(someParam, anotherParam, o));
Run Code Online (Sandbox Code Playgroud)

虽然我不确定它到底有多大用处.如果offset是全局的东西,你可能想要注入它而不是通过使它成为它们所属的类的字段而将它传递给这些函数.

  • 如果您不想要返回值,请尝试"Action"而不是"Func". (2认同)