[英]Func<T> with out parameter
Can I pass a method with an out parameter as a Func?我可以将带有 out 参数的方法作为 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. Func 需要一个类型,所以 out 不会在那里编译,并且调用 listFunction 需要一个 int 并且不允许 out in。
Is there a way to do this?有没有办法做到这一点?
ref
and out
are not part of the type parameter definition so you can't use the built-in Func
delegate to pass ref
and out
arguments. ref
和out
不是类型参数定义的一部分,因此您不能使用内置的Func
委托来传递ref
和out
参数。 Of course, you can declare your own delegate if you want:当然,如果需要,您可以声明自己的委托:
delegate V MyDelegate<T,U,V>(T input, out U output);
Why not create a class to encapsulate the results?为什么不创建一个类来封装结果?
public class Result
{
public IList<Foo> List { get; set; }
public Int32 Count { get; set; }
}
The Func
family of delegates (or Action
for that matter) are nothing but simple delegate types declared like Func
委托系列(或Action
就此而言)只不过是简单的委托类型,声明如下
//.NET 4 and above
public delegate TResult Func<out TResult>()
public delegate TResult Func<in T, out TResult>(T obj)
//.NET 3.5
public delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 obj1, T2 obj2, T3 obj3)
etc. 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.等。委托本身可以有 out/ref 参数,所以在你的情况下,它只是你自己自定义实现的问题,正如其他答案所指出的那样。 As to why Microsoft did not pack this by default, think of the sheer number of combinations it would require.
至于为什么微软没有默认打包,想想它需要的绝对数量的组合。
delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(T1 obj1, out T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, out T2 obj2)
for just two parameters.仅用于两个参数。 We have not even touched
ref
.我们甚至没有接触过
ref
。 It would actually be cumbersome and confusing for developers.对于开发人员来说,这实际上会很麻烦且令人困惑。
您可以将它包装在一个 lambda/delegate/function/method 中,该方法暴露了正确的接口并称为 FindForBar,但我怀疑 FindForBar 已将其视为 out 参数作为一个原因,因此您需要确保将这些信息扔掉ok/safe/desirable/有正确的结果(即使您可以直接传入 FindForBar,您也需要确定这一点)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.