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

时间:2016-06-20 00:39:07

标签: c# generics dictionary types

我希望能够实现密钥为Type且值为Func<T>的字典,其中T是与密钥类型相同的对象:< / p>

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>的类型,这些类型将返回该值:

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

我如何实施和实施?

1 个答案:

答案 0 :(得分: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>;
    }
}