I'd like to be able to implement a dictionary with a key of Type
and a value of Func<T>
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 would be populated with types that would reference a Func<T>
which would return that value :
int Bar = TypeDictionary[ typeof( int ) ]( );
string Baz = TypeDictionary[ typeof( string ) ]( );
How can I go about implementing and enforcing this?
This is about as close as you're going to get:
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>;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With