是否可以在字典中存储Func <T>?

Wil*_*ill 6 c# generics dictionary types

我希望能够实现一个字典,其中键的Type值和Func<T>where 值T是与键相同类型的对象:

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" );
Run Code Online (Sandbox Code Playgroud)

因此,基本上,字典将填充引用Func<T>将返回该值的类型:

int Bar = TypeDictionary[ typeof( int ) ]( );
string Baz = TypeDictionary[ typeof( string ) ]( );
Run Code Online (Sandbox Code Playgroud)

我该如何实施和执行此操作?

Rob*_*Rob 7

这差不多就像你要得到的那样:

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>;
    }
}
Run Code Online (Sandbox Code Playgroud)