如何使用委托构造一个TransformManyBlock [英] How to construct a TransformManyBlock with a delegate
问题描述
我是C#TPL和DataFlow的新手,我正在努力研究如何实现TPL DataFlow TransformManyBlock
.我正在将其他一些代码转换为DataFlow.我的(简化的)原始代码是这样的:
I'm new to C# TPL and DataFlow and I'm struggling to work out how to implement the TPL DataFlow TransformManyBlock
. I'm translating some other code into DataFlow. My (simplified) original code was something like this:
private IEnumerable<byte[]> ExtractFromByteStream(Byte[] byteStream)
{
yield return byteStream; // Plus operations on the array
}
在另一种方法中,我会这样称呼它:
And in another method I would call it like this:
foreach (byte[] myByteArray in ExtractFromByteStream(byteStream))
{
// Do stuff with myByteArray
}
我正在尝试创建一个 TransformManyBlock
来生成多个较小的数组(实际上是数据包),这些数组来自较大的输入数组(实际上是一个二进制流),因此in和out都是类型 byte []
.
I'm trying to create a TransformManyBlock
to produce multiple little arrays (actually data packets) that come from the larger input array (actually a binary stream), so both in and out are of type byte[]
.
我尝试了下面的内容,但我知道我记错了.我想使用与以前相同的功能构造此块,并在其周围包裹 TransformManyBlock
.我收到一个错误消息通话不明确..."
I tried what I've put below but I know I've got it wrong. I want to construct this block using the same function as before and to just wrap the TransformManyBlock
around it. I got an error "The call is ambiguous..."
var streamTransformManyBlock = new TransformManyBlock<byte[], byte[]>(ExtractFromByteStream);
推荐答案
编译器在推断类型时遇到麻烦.您需要明确指定委托类型以消除呼叫的歧义:
The compiler has troubles with inferring the types. You need to either specify the delegate type explicitly to disambiguate the call:
var block = new TransformManyBlock<byte[], byte[]>(
(Func<byte[], IEnumerable<byte[]>>) ExtractFromByteStream);
或者您可以使用调用该方法的lambda表达式:
Or you can use a lambda expression that calls into that method:
var block = new TransformManyBlock<byte[], byte[]>(
bytes => ExtractFromByteStream(bytes));
这篇关于如何使用委托构造一个TransformManyBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!