Is it possible to save Func <T> in the dictionary?

I would like to be able to implement a dictionary with a Type key and a Func<T> value, where T is an object of the same type as the key:

 Dictionary<Type, Func<T>> TypeDictionary = new Dictionary<Type, Func<T>>( ) /*Func<T> returns an object of the same type as the Key*/ TypeDictionary.Add( typeof( int ), ( ) => 5 ); TypeDictionary.Add( typeof( string ), ( ) => "Foo" ); 

So basically, the dictionary will be filled with types that will reference Func<T> , which will return this value:

 int Bar = TypeDictionary[ typeof( int ) ]( ); string Baz = TypeDictionary[ typeof( string ) ]( ); 

How can I implement and provide this?

+6
source share
1 answer

This is about as close as you are going:

 void Main() { var myDict = new MyWrappedDictionary(); myDict.Add(() => "Rob"); var func = myDict.Get<string>(); Console.WriteLine(func()); } public class MyWrappedDictionary { private Dictionary<Type, object> innerDictionary = new Dictionary<Type, object>(); public void Add<T>(Func<T> func) { innerDictionary.Add(typeof(T), func); } public Func<T> Get<T>() { return innerDictionary[typeof(T)] as Func<T>; } } 
+7
source

All Articles