1

抱歉,我不确定这个标题的最佳名称是什么...

我是 .NET 编程的新手(有一点 Java 背景),我尝试开发一个简单的类型化处理队列。

我将我的对象放在第一个 ActionQueue 中。通过内部逻辑,只有一个IActioninActionQueue处理对象并将其推送到 next 中ActionQueue。每个ActionQueue都充满了TaskBlockingCollection(但这并不重要):

Object
...
ActionQueue[IPrepare, IPrepare]
...
ActionQueue[IDownload, IDownload]
...
ActionQueue[ISave]
...
ProcessedObject

我试图实现的是:

  • 使ActionQueue通用,因此只能IActions为作业注册相同的子接口(我List<T>用来存储操作)
  • 具有将输出与另一个输入Next绑定的属性ActionQueueActionQueue

我的简化代码如下所示:

# SETUP

interface IPrepare: IAction {}
interface IDownload: IAction {}
interface ISave: IAction {}

public interface IActionQueue<in T> where T: IAction {
    IActionQueue<IAction> Next {get;set;} # it can be any action queue
    void Register(T action);
    void Run();
}

class PrepareFromDb : IPrepare {...}
class PrepareFromSettings : IPrepare {...}
class DownloadLocal : IDownload{...}
class DownloadHttp : IDownload{...}
class SaveLocal: ISave {...}

# IN MAIN METHOD

ActionQueue<IPrepare> prepareActions = new ActionQueue<IPrepare>();
prepareActions.Register(new PrepareFromDb(config));
prepareActions.Register(new PrepareFromSettings());

ActionQueue<IDownload> downloadActions = new ActionQueue<IDownload>();
downloadActions.Register(new DownloadLocal());
downloadActions.Register(new DownloadHttp());

ActionQueue<ISave> saveActions = new ActionQueue<ISave>();
saveActions.Register(new SaveLocal(RootPath));

# TRICKY PART THAT FAILS

prepareActions.Next = downloadActions # pass `prepare`d items to `download` queue
downloadActions.Next = saveActions # pass `download`ed items to `save` queue

如果我声明IActionQueueinterface ITrackQueue<out T> where T: ITrackTransformer(note out ),Main函数没有显示错误,但 void Register(T action)现在显示错误。

因为它是内部库的代码并且我是唯一的用户,所以我可以删除所有通用的东西并编译它。但我总是尽可能严格地编写代码。

或者我可以使用ActionQueue's internal BlockingCollectionqueue 作为Next属性,但我不喜欢泄露内部实现,因为它破坏了封装。

所以问题是。实现这一点的最类型安全的方法是什么?

4

0 回答 0