mardi 14 février 2023

Use non-generic method of Hashset through reflection

I want to be able to call the Hashset.ExceptWith() method using reflection but I can't make it happen.

I can't create a generic method. It seems it isn't a generic method. I also can't seem to call the method itself using invoke.

Does anyone know how to do this?

var newSet = pi.GetValue(newItem);
var existingSet = pi.GetValue(existingItem);
MethodInfo methodExcept = typeof(HashSet<>).GetMethod("ExceptWith");

//The next line throws: Void ExceptWith(System.Collections.Generic.IEnumerable`1[T]) is not a GenericMethodDefinition. 
//MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.'
MethodInfo genericExcept = methodExcept.MakeGenericMethod(pi.GetType().GetGenericTypeDefinition().UnderlyingSystemType);

//The next line throws 'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'
methodIntersect.Invoke(existingSet, new[] { newSet });
//The next line is not possible since instantiation of the variable doesn't work
genericIntersect.Invoke(existingSet, new[] { newSet });




Aucun commentaire:

Enregistrer un commentaire