【发布时间】:2016-10-21 03:56:42
【问题描述】:
我希望能够实现一个带有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> 的类型,该 Func<T> 将返回该值:
int Bar = TypeDictionary[ typeof( int ) ]( );
string Baz = TypeDictionary[ typeof( string ) ]( );
我该如何实施和执行?
【问题讨论】:
-
字典中所有元素的
T是否相同? -
没有强类型。无论如何,这没有意义。
var thing = TypeDictionary[someType];的类型是什么?如果你有someType = typeof(int),它可能相当明显。但是,如果它取自obj.GetType()并将obj转换为object会发生什么?您可以添加限制类型的方法,但您总是必须以Dictionary<Type, object>()结尾并在检索值时强制转换它。 -
没有。字典中的每个条目的 T 应该不同...让我更改我的问题以反映...
-
@Dai 如果是字典,则只有一个条目。
-
@meJustAndrew
TypeDictionary.Add( typeof( int ), int Bar => Bar * 5 )int Baz = TypeDictionary[typeof( int )]( 12 );(当然,这是一个非常简单的例子,但旨在说明这一点 - 字典旨在存储将根据操作和返回值的函数关于键的类型)。
标签: c# generics dictionary types