你可以创建一个抽象类型,该类型实现与目标块类型相同的接口(
TransformBlock
实现
IPropagatorBlock
和
IReceivableSourceBlock
)。
而不是复制该块的行为,将所有方法调用委托给该类型的一个
innerBlock
。
public abstract class AbstractMultiplyBlock<TInput, TOutput>
: IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>
{
private readonly TransformBlock<TInput, TOutput> innerBlock;
protected AbstractMultiplyBlock(TransformBlock<TInput, TOutput> innerBlock)
{
this.innerBlock = innerBlock;
}
}
这个抽象类具有与
TransformBlock
类相同的属性和方法。现在,创建派生类型,将
TransformBlock
的实例传递给基础构造函数。
public sealed class MultiplyByTwoBlock : AbstractMultiplyBlock<int, int>
{
public MultiplyByTwoBlock()
: base(new TransformBlock<int, int>(x => x * 2))
{
}
}
public sealed class MultiplyByThreeBlock : AbstractMultiplyBlock<int, int>
{
public MultiplyByThreeBlock()
: base(new TransformBlock<int, int>(x => x * 3))
{
}
}
使用方法与其他任何 TransformBlock
实例相同。
var calculator1 = new MultiplyByTwoBlock();
var calculator2 = new MultiplyByThreeBlock();
calculator1.LinkTo(calculator2);
calculator1.Post(10);
var x = calculator2.Receive();
附录
AbstractMultiplyBlock
的完整源代码
public abstract class AbstractMultiplyBlock<TInput, TOutput>
: IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>
{
private readonly TransformBlock<TInput, TOutput> innerBlock;
protected AbstractMultiplyBlock(TransformBlock<TInput, TOutput> innerBlock)
{
this.innerBlock = innerBlock;
}
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source,
bool consumeToAccept)
{
return ((ITargetBlock<TInput>)innerBlock).OfferMessage(messageHeader, messageValue, source, consumeToAccept);
}
public void Complete()
{
innerBlock.Complete();
}
public void Fault(Exception exception)
{
((IDataflowBlock)innerBlock).Fault(exception);
}
public Task Completion
{
get { return innerBlock.Completion; }
}
public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
{
return innerBlock.LinkTo(target, linkOptions);
}
public TOutput ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out bool messageConsumed)
{
return ((ISourceBlock<TOutput>)innerBlock).ConsumeMessage(messageHeader, target, out messageConsumed);
}
public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
return ((ISourceBlock<TOutput>)innerBlock).ReserveMessage(messageHeader, target);
}
public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
((ISourceBlock<TOutput>)innerBlock).ReleaseReservation(messageHeader, target);
}
public bool TryReceive(Predicate<TOutput> filter, out TOutput item)
{
return innerBlock.TryReceive(filter, out item);
}
public bool TryReceiveAll(out IList<TOutput> items)
{
return innerBlock.TryReceiveAll(out items);
}
}
NoOpActionBlock
已经存在于DataflowBlock.NullTarget()
中了。 - svick