Perhaps the easiest way is to explicitly specify the formula from TUto TVin the calling place, like here, after option 1. If you prefer to hide the conversion details behind the scenes so that it works wherever you call the extension method to avoid repeating the formula, then the interface is suitable as it can be used as a limitation for the extension method:
class Program
{
static void Main(string[] args)
{
IEnumerable<U> uSequence = new List<U>();
IEnumerable<V> vSequence1 = uSequence.To(u => new V(u));
IEnumerable<V> vSequence2 = uSequence.To<U, V>();
}
}
public static class Extensions {
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source, Func<TU,TV> transform)
{
return source.Select(tu => transform(tu));
}
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) where TV : IBuildableFrom<TV, TU>, new()
{
return source.Select(tu => new TV().BuildFrom(tu));
}
}
public interface IBuildableFrom<TV, TU>
{
TV BuildFrom(TU tu);
}
public class U { }
public class V : IBuildableFrom<V, U>
{
public V BuildFrom(U u)
{
return this;
}
public V(U u) { }
public V() { }
}
source
share