How to cast IDictionary<string, object> to IDictionary<string, MyType>
-
07-07-2021 - |
Pergunta
I'm using the default MemoryCache
, which works fine for my purposes. However the GetValues()
method returns IDictionary<string, object>
Is there a quick way to cast this to IDictionary<string, MyType>
?
Solução
Use ToDictionary
:
ToDictionary(k => k.Key, k => (MyType)k.Value)
Outras dicas
Do your own GetValues
method that call to the original one. For each result, do the cast to the second returned value (the object one) and generate your own casted IDictionary
.
This would mean that you can only store objects of type MyType
inside this cache. But if this is the case you could have a wrapper method:
public static IDictionary<string, MyType> GetValues(IEnumerable<string> keys)
{
return MemoryCache.Default.GetValues(keys).ToDictionary(x => x.Key, x => x.Value as MyType);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow