我希望能够实现一个键为 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/