Registry of templated types in C#
I have an inte开发者_如何学运维rface IDataStream and different implementations of it (i.E. DataStream<T>
).
I need to make a class DataStreamManager which has a registry functionality (Find(Key)
) for all DataStreams cuttently available (meaning, the registry should contain refs to DataStream<int>
, DataStream<SomeObject>
...), and the DataStreamManager must be singleton.
Does anyone have an idea how to make such a registry in C#?
You can leverage IDictionary<TKey, TValue>
for this purposes:
Te question is what would be a Key to identify a concrete data stream?
public sealed class DataStreamManager
{
var dataStreamsMap = new Dictionary<Type, IDataStream>
{
{ typeof(int), new DataStream<int>() }
}
public IDataStream Get<T>()
{
IDataStream dataStream = null;
Type key = typeof(T);
if (dataStreamsMap.Contains(key))
{
dataStream = dataStreamsMap[key];
}
return dataStream;
}
}
And then use it:
var manager = new DataStreamManager();
var dataStream = manager.Get<int>();
精彩评论