Are there any good algorithms for determining the "best" type to instantiate in order to fulfill a request?
For instance say I have the following classes:
public interface ISometype<T> {}
public class SomeTypeImpl<T>:ISometype<T> {}
public class SomeSpecificTypeImpl<T>:ISometype<T> where T: ISpecificSpecifier {}
public interface ISpecificSpecifier { }
Suppose a caller wants the best implementation type for this interface. I could implement this particular method like this:
public Type GetBestImplementationType(Type genericParam) {
try {
return typeof(SomeSpecificTypeImpl<>).MakeGenericType(genericParam);
} catch(ArgumentException) {}
return typeof(SomeTypeImpl<>).MakeGenericType(genericParam);
}
While this implementation will work for this particular case I am more concerned about the generalizations where there may be more than one potential specific implementation and multiple generic parameters:
public Type GetBestImplementationType(Type[] genericParams, Type[] potentialTypes) {
foreach(var t in potentialTypes) {
try {
return t.MakeGenericType(genericParams);
} catch(ArgumentException) {}
}
throw new Exception("unable to find specific implementation type");
}
This should work given the potentialTypes array is provided from most to least specific order. So for answers, either an algorithm implementing this method (or something sufficiently similar) or an algorithm implementing the sort that I could use in this method would do.
[warning: code untested, syntax/logic errors may exist]