Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- namespace ConsoleApplication1 {
- public class Koos {
- public string name { get; set; }
- }
- public class Jan {
- public string Name { get; set; }
- }
- public class TransformModifier : ExpressionVisitor {
- ParameterExpression param; // this stops the class from being thread-safe!
- public Expression Modify(Expression expression) {
- return Visit(expression);
- }
- protected override Expression VisitMember(MemberExpression node) {
- if (node.Expression.Type == typeof(Jan)) {
- // redirect! 'param' was assigned previously, in VisitLambda
- var redir = Expression.MakeMemberAccess(param, typeof(Koos).GetMember("name")[0]);
- return redir;
- } else return base.VisitMember(node);
- }
- protected override Expression VisitLambda<T>(Expression<T> node) {
- // convert "Jan" parameter to "Koos" parameter.
- // don't need to type-check; static type-checking should take care of this for me?
- param = Expression.Parameter(typeof(Koos));
- return Expression.Lambda<Func<Koos, bool>>(Visit(node.Body), param);
- }
- protected override Expression VisitBinary(BinaryExpression node) {
- return base.VisitBinary(Expression.MakeBinary(node.NodeType, Visit(node.Left), Visit(node.Right)));
- }
- }
- public class Program {
- static void Main(string[] args) {
- Expression<Func<Jan, bool>> exp = j => j.Name == "Jan";
- var janCompiled = exp.Compile();
- Console.WriteLine("Expect this to be false: {0}", janCompiled(new Jan() { Name = "Bob" }));
- Console.WriteLine("Expect this to be true: {0}", janCompiled(new Jan() { Name = "Jan" }));
- Console.WriteLine(exp);
- foreach (var p in exp.Parameters) Console.WriteLine(p.Type);
- var t = new TransformModifier();
- var mod = (Expression<Func<Koos,bool>>)t.Modify(exp);
- Console.WriteLine("Modified:");
- foreach (var p in mod.Parameters) Console.WriteLine(p.Type);
- Console.WriteLine(mod);
- var compiled = mod.Compile();
- Console.WriteLine("Expect this to be false: {0}", compiled(new Koos() { name = "Bob" }));
- Console.WriteLine("Expect this to be true: {0}", compiled(new Koos() { name = "Jan" }));
- Console.ReadKey();
- }
- }
- }
Add Comment
Please, Sign In to add comment