In C #, how can I make a generic dictionary?

Suppose I have a generic class Foo<T> .

What I want to do is create a singleton for each of the set T, and then quickly get them later T.

in pseudo code

 STORE new Foo<int> STORE new Foo<MyClass> GET instance for MyClass -> returns the Foo<MyClass> created above. 

In Java, I would make a dictionary with a type for the key and Foo<*> for the value.

What is equivalent magic in C #?

+4
source share
2 answers
 Dictionary<Type, object> Dict = new Dictionary<Type, object>(); void Store<T>(Foo<T> foo) { Dict.Add(typeof(T), foo); } Foo<T> Retrieve<T>() { return Dict[typeof(T)] as Foo<T>; } 
+9
source

There are two ways that a type can be set to a method: as a Type parameter or as a parameter of a general type. In the first case, if the general class Foo<T> inherited from the base class (for example, FooBase ), which is not common for type T, you can use Dictionary<Type,FooBase> . The FooBase class can include all members (possibly abstract or virtual ) of Foo<T> whose signature does not depend on T , so code that is given a Type object for an arbitrary type but does not have a parameter of a general type will be able to do FooBase all that could be done without having a parameter of a general type. Please note: if you have a Type object and want to use it as if it were a general type, you usually need to use Reflection and build either a delegate or an instance of a class of a common class with a filled type parameter; once this has been done, you can use the second approach below.

If you have a common type of parameters (for example, one writes the method T GetThing<T>(whatever) , you can define a static general class ThingHolder<T> with a static field T theThing . In this case, for any type TT , ThingHolder<TT>.theThing will be a TT type field. With this field you can do everything you can do with TT .

+1
source

Source: https://habr.com/ru/post/1497832/


All Articles