开发者

Can I pass a non-generic type where a generic type is expected?

I want to define a set of classes that collect and persist data. I want to call them either on-demand basis, or in a chain-of-responsibility fashion, as the caller pleases.

To support the chaining, I have declared my interface like so:

interface IDataManager<T, K>
{
    T GetData(K args);
    void WriteData(Stream stream);
    void WriteData(T data, Stream stream);

    IDataCollectionPolicy Policy;

    IDataManager<T, K> NextDataManager;
}

But the T's and K's for each concrete types will be different. If I give it like this:

IDataManager<T, K> NextDataManager;

I assume that the calling code will only be able to chain types that have the same T's and K's. Is there a way I can have it chain any type of IDataManager?

One thing that occurs to me is to have IDataManager inherit from a non-generic IDataManager like so:

interface IDataManager { }

interface IDataManager<T, K>: IDataManager
{
    T GetData(K args);
    void WriteData(Stream stream);
    void WriteData(T data, 开发者_如何学编程Stream stream);

    IDataCollectionPolicy Policy;

    IDataManager NextDataManager;
}

Is this going to work?


Splitting an interface into a generic and a non-generic part is a common pattern, especially if you move non-generic methods to the non-generic interface:

interface IDataManager
{
    void WriteData(Stream stream);
    IDataCollectionPolicy Policy { get; set; }
    IDataManager NextDataManager { get; set; }
}

interface IDataManager<T, K> : IDataManager
{
    T GetData(K args);
    void WriteData(T data, Stream stream);
}


Yes, your proposed solution is correct. The general practice is (as you describe) to create a non-generic base class/interface, then a generic class/interface that implements/inherits from it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜