using System; using System.Linq.Expressions; namespace RosettaUI { public static class CastGetter { public static IGetter Create(IGetter getter) { return getter == null ? null : new CastGetter(getter); } public static IGetter Create(IGetter getter, Type fromType, Type toType) { if (getter == null) return null; var castGetterType = typeof(CastGetter<,>).MakeGenericType(fromType, toType); return (IGetter) Activator.CreateInstance(castGetterType, getter); } } public class CastGetter : ChildGetter { public CastGetter(IGetter parentGetter) : base(parentGetter) { } protected override TTo GetFromChild(TFrom parent) { return CastFunc(parent); } #region static private static readonly Func CastFunc; static CastGetter() { var from = Expression.Parameter(typeof(TFrom)); var cast = Expression.Convert(from, typeof(TTo)); CastFunc = Expression.Lambda>(cast, from).Compile(); } #endregion } }