Line data Source code
1 : #region Copyright
2 : // // -----------------------------------------------------------------------
3 : // // <copyright company="Chinchilla Software Limited">
4 : // // Copyright Chinchilla Software Limited. All rights reserved.
5 : // // </copyright>
6 : // // -----------------------------------------------------------------------
7 : #endregion
8 :
9 : using System;
10 : using System.Linq.Expressions;
11 :
12 : namespace Cqrs.Infrastructure
13 : {
14 : /// <summary>
15 : /// Adjusts <see cref="Expression"/> using <see cref="Expression.Convert(System.Linq.Expressions.Expression,System.Type)"/>
16 : /// </summary>
17 : public static class DelegateAdjuster
18 1 : {
19 : /// <summary>
20 : /// If <typeparamref name="TDerived"/> equals <typeparamref name="TBase"/> then <paramref name="source"/> is compiled using <see cref="Expression{TDelegate}.Compile()"/>
21 : /// Otherwise <paramref name="source"/> is converted to type <typeparamref name="TDerived"/> from <typeparamref name="TBase"/>
22 : /// </summary>
23 : /// <typeparam name="TBase">The source <see cref="Type"/>.</typeparam>
24 : /// <typeparam name="TDerived">The target <see cref="Type"/>.</typeparam>
25 : /// <param name="source">The delegate to adjust.</param>
26 1 : public static Action<TBase> CastArgument<TBase, TDerived>(Expression<Action<TDerived>> source)
27 : where TDerived : TBase
28 : {
29 : if (typeof(TDerived) == typeof(TBase))
30 : {
31 : return (Action<TBase>)((Delegate)source.Compile());
32 : }
33 :
34 : ParameterExpression sourceParameter = Expression.Parameter(typeof(TBase), "source");
35 : Expression<Action<TBase>> result = Expression.Lambda<Action<TBase>>
36 : (
37 : Expression.Invoke(source, Expression.Convert(sourceParameter, typeof(TDerived))),
38 : sourceParameter
39 : );
40 : return result.Compile();
41 : }
42 : }
43 : }
44 :
|