函数没有参数
我可以将带有 out 参数的方法作为 Func 传递吗?
public IList<Foo> FindForBar(string bar, out int count) { }
// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }
Func 需要一个类型,因此 out 不会在那里编译,并且调用 listFunction 需要一个 int 并且不允许 out in。
有没有办法做到这一点?
Can I pass a method with an out parameter as a Func?
public IList<Foo> FindForBar(string bar, out int count) { }
// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }
Func needs a type so out won't compile there, and calling listFunction requires an int and won't allow an out in.
Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ref
和out
不是类型参数定义的一部分,因此您不能使用内置Func
委托来传递ref
和out
参数。当然,如果您愿意,您可以声明自己的委托:ref
andout
are not part of the type parameter definition so you can't use the built-inFunc
delegate to passref
andout
arguments. Of course, you can declare your own delegate if you want:为什么不创建一个类来封装结果呢?
Why not create a class to encapsulate the results?
委托的
Func
系列(或就此而言的Action
)只不过是声明为等的简单委托类型。这样的委托可以具有 out/ref 参数,所以在您的情况下正如其他答案所指出的那样,这只是您自己自定义实现的问题。 至于为什么微软没有默认打包这个,想想它需要的组合数量之多。
仅两个参数。 我们甚至没有触及
ref
。 对于开发人员来说,这实际上会很麻烦且令人困惑。The
Func
family of delegates (orAction
for that matter) are nothing but simple delegate types declared likeetc. Delegates as such can have out/ref parameters, so in your case its only a matter of custom implementation by yourself as other answers have pointed out. As to why Microsoft did not pack this by default, think of the sheer number of combinations it would require.
for just two parameters. We have not even touched
ref
. It would actually be cumbersome and confusing for developers.您可以将其包装在公开正确接口并调用 FindForBar 的 lambda/delegate/function/method 中,但我怀疑 FindForBar 已将其计为 out 参数作为原因,因此您需要确保丢弃该信息ok/safe/desirable/有正确的结果(即使您可以直接传入 FindForBar,您也需要确定这一点)。
You could wrap it in a lambda/delegate/function/method that exposed the right interface and called FindForBar, but I suspect that FindForBar has count as an out parameter as a reason, so you'd need to be sure throwing that information away was ok/safe/desirable/had the right results (you'd need to be sure of this even if you could just directly pass in FindForBar).