mardi 21 novembre 2017

Conversion from object to List

This question already has an answer here:

I am trying to implement the function public IEnumerable<T> ConvertFrom<T>(object setOfElements, Type sourceType) where T : MyInterface, where:

  • setOfElements is given as an object, but it actually is an HashSet of sourceType
  • sourceType is the original type of source elements
  • T is the output desired type, and it inherits from MyInterface
  • MyInterface contains the method public T BuildFrom(sourceType x), which can be used to map a sourceType object into a T object

In other words, I need to perform something like:

return ((IEnumerable)setOfElements).Cast<sourceType>()
                                   .Select(x => new T().BuildFrom(x))

That line of code works perfectly when I know the types at compile time, but with generic types I need to invoke that using reflection and I can't succeed.

Please consider that my issue is not how to generally call a generic method via reflection, but which parameters/calls to nest to perform that behavior





Aucun commentaire:

Enregistrer un commentaire