jeudi 12 juillet 2018

How to program when type arguments of generic type are known at runtime?

I have a data store code base which use generic types for apis so that users can program nicely against Key and Value.

E.g.

db.AddAsync<Key,Value>(Key k, Value v)
DBEnumerator<Key,Value> db.GetAsyncEnumerator<Key,Value>()

Now, for some feature, we have these Key and Value types loaded from another dll at runtime. So, i have

Type keyType = ..., valueType = ...;
var enumerator = db.GetType().GetMethod("GetAsyncEnumerator").MakeGenericMethod(new Type[] { keyType, valueType });

Now, how can i cast, enumerator to DBEnumerator<Key,Value> where Key is value of keyType and Value is value of valueType ?

I have more 50 lines and i don't want to use reflection all the way. What are the best practices and helper methods in this situation ?





Aucun commentaire:

Enregistrer un commentaire