【问题标题】:Is it possible to store a Func<T> within a dictionary?是否可以将 Func<T> 存储在字典中?
【发布时间】:2016-10-21 03:56:42
【问题描述】:

我希望能够实现一个带有Type 键和Func&lt;T&gt; 值的字典,其中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&lt;T&gt; 的类型,该 Func&lt;T&gt; 将返回该值:

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

我该如何实施和执行?

【问题讨论】:

  • 字典中所有元素的T 是否相同?
  • 没有强类型。无论如何,这没有意义。 var thing = TypeDictionary[someType]; 的类型是什么?如果你有someType = typeof(int),它可能相当明显。但是,如果它取自 obj.GetType() 并将 obj 转换为 object 会发生什么?您可以添加限制类型的方法,但您总是必须以 Dictionary&lt;Type, object&gt;() 结尾并在检索值时强制转换它。
  • 没有。字典中的每个条目的 T 应该不同...让我更改我的问题以反映...
  • @Dai 如果是字典,则只有一个条目。
  • @meJustAndrew TypeDictionary.Add( typeof( int ), int Bar =&gt; Bar * 5 ) int Baz = TypeDictionary[typeof( int )]( 12 ); (当然,这是一个非常简单的例子,但旨在说明这一点 - 字典旨在存储将根据操作和返回值的函数关于键的类型)。

标签: c# generics dictionary types


【解决方案1】:

这与您将要得到的差不多:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2018-10-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多