I had a problem (possibly due to my ignorance of C # generics) in getting an unclosed common type. I have several methods that look more like the following, except for the authentication interface used.
public IEnumerable<IDeleteValidator<T>> GetDeleteValidators<T>() { var validatorList = new List<IDeleteValidator<T>>(); foreach (var type in GetRecursiveBaseTypesAndInterfaces(typeof(T))) { var validatorType = typeof(IDeleteValidator<>).MakeGenericType(type); var validators = ObjectFactory .GetAllInstances(validatorType).Cast<IDeleteValidator<T>>(); validatorList.AddRange(validators); } return validatorList; }
The GetRecursiveBaseTypesAndInterfaces method executes, as it says, and collects all the base types and interfaces of this type. So what I ultimately do is get the open type of the explicit validator interface and get its type closed for each of the base classes and interfaces of the original type T. This works fine, however, I would like to clear my code and execute it in a more general form higher
knowing that any validator T will expand the validator (as below)
public interface IDeleteValidator<in T> : IValidator<T> {}
My incomplete attempt to a generic version of the method described above looks like this:
public IEnumerable<TValidator> GetValidators<T, TValidator>() where TValidator : IValidator<T> { var validatorList = new List<TValidator>(); foreach (var type in GetRecursiveBaseTypesAndInterfaces(typeof(T))) { var unclosedType = ??? var validatorType = typeof(unclosedType).MakeGenericType(type); var validators = ObjectFactory .GetAllInstances(validatorType).Cast<TValidator>(); validatorList.AddRange(validators); } return validatorList; }
How to define unclosedType (or restructure a method) to do the same job as the original method, with a call
GetValidators<Whatever, IDeleteValidator<Whatever>>();
Or could I refine my method more, since it would be enough to call the next call?
GetValidators<IDeleteValidator<Whatever>>();
source share