我对TPL数据流是全新的,如果这是一个简单的问题,请原谅我。

我有一个带有基类的输入缓冲区。如何根据派生类型从那里分支到一个块?因此,例如:

var inputBlock = new BufferBlock<EventBase>();
//if EventBase is Meeting then go to block X
//if EventBase is Appointment the go to block Y

谢谢!

最佳答案

您可以将谓词发送到LinkTo方法以区分项目。但是,您需要从每个块内的EventBase向下转换,以使用特定于该类型的逻辑:

var inputBlock = new BufferBlock<EventBase>();
var meetingBlock = new ActionBlock<EventBase>(
    eventBase =>
    {
        var meeting = eventBase as Meeting;
        //...
    });
var appointmentBlock = new ActionBlock<EventBase>(
    eventBase =>
    {
        var appointment = eventBase as Appointment;
        //...
    });

inputBlock.LinkTo(meetingBlock, eventBase => eventBase is Meeting);
inputBlock.LinkTo(appointmentBlock, eventBase => eventBase is Appointment);

但是正如Servy指出的那样,您可能应该避免这种情况,并设计类型以支持多态。

10-06 13:27