vendredi 4 mars 2022

cast objects to a known interface with generic type parameter where that type parameter is given as type variable at runtime

I am doing some reflection stuff. I have the following situation:

  • I have a variable Type myType with some runtime value (e.g. string or List<int>).
  • I have two variables object a and object b for which I know that they are of type IImmutableSet<myType>. (So if myType=string they'd be IImmutableSet<string>, if myType=List<int> they'd be IImmutableSet<List<int>> and so on.)

How can I cast them?


Motivation:

I want to do a comparison of a and b by content, i,e.

  • check that both their size is equal. For that, I need a Count property (or equivalent property/method).
  • check that a contains all elements of b. For that, I need a Contains(...) method.

If I had ISet<T>s, I'd just cast them to ICollection and use that interface's Count and Contains(...).

But since IImmutableSet<T> does not implement any non-generic collection interface, I need to cast a and b to IImmutableSet<myType> (or IReadOnlyCollection<myType>). That syntax doesn't work because it expects a compile-time constant type.

--

Another thought... if casting isn't possible, I'd be happy with being able to call the said methods. Since I'm already doing heavy reflection, I don't care about speed.





Aucun commentaire:

Enregistrer un commentaire