我希望能够使用Type的键和Func< T>的值来实现字典.其中T是与键相同类型的对象:
@H_403_2@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" );
因此,基本上,字典将填充有引用Func< T>的类型.哪会返回该值:
@H_403_2@int Bar = TypeDictionary[ typeof( int ) ]( ); string Baz = TypeDictionary[ typeof( string ) ]( );我该如何实施和执行此操作?
解决方法
这差不多就像你要得到的那样:
@H_403_2@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>;
}
}