c# - 是否可以将 Func<T> 存储在字典中?

标签 c# generics dictionary types

我希望能够实现一个键为 Type 的字典值 Func<T>其中 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" );

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

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

我该如何着手实现和强制执行?

最佳答案

这与您将要获得的结果差不多:

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>;
    }
}

关于c# - 是否可以将 Func<T> 存储在字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913293/

相关文章:

c# - Java和C#之间的通信

c# - Entity Framework 导航属性上的 OrderBy(一对多)

c# - Azure 函数无法加载 'System.UriTemplate'

c# - 我可以有可变数量的通用参数吗?

java - 如果我们不知道容器类型中元素的类型,如何实现迭代器?

c++,通过使用for循环在 map 内部存储键和值

c++ - 在 C++ 中按空格拆分字符串的最快方法

c# - 链接 Task.WhenAll()

c# - 集合类型名称中的 '1 是什么

c# - 使用 LINQ 按一个字段分组,基于组求和并存储在字典中