mercredi 28 janvier 2015

How to pass in a generic type using a variable working it out at runtime?

I wish to make a generic extension method :



public static IList<ValidationResult> ValidateMany<T>(this IValidator validator, IList objectsToValidate)
{
var results = new List<ValidationResult>();
foreach (var obj in objectsToValidate)
{
var validationResult = validator.Validate((T) obj);
results.Add(validationResult);
}
return results;
}


I would like T to be passed in. That may seem easy by adding a template param, but then from the calling code I would like to do :



// calling code
var typeOfT = WorkOutTypeFromObjects(objectsToValidate);
var objectsToValidate = ...;
var results = validator.ValidateMany<typeOfT>(objectsToValidate);


the top line there is the critical part that is hard to get, I need some dynamic way of working out the type and passing it in the T param. Or is there a good alternative?






Aucun commentaire:

Enregistrer un commentaire