zoukankan      html  css  js  c++  java
  • C# 表达式树学习笔记

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
    
        /// <summary>
        /// 动态表达式树
        /// </summary>
        public partial class Form1 : Form
        {
            class aa
            {
                public string test
                {
                    get;
                    set;
                }
            }
    
            public Form1()
            {
                InitializeComponent();
            }
    
            /// <summary>
            /// 示例地址: http://www.cnblogs.com/feichexia/archive/2013/05/28/3104832.html
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
               //A.
               //aa a1 = new aa ();
               //typeof(aa).GetProperty("test").SetValue(a1, "test2", null);
    
    
                //B.MessageBox.Show(a1.test);
                //ParameterExpression  p1 = Expression.Parameter(typeof(int), "a");
                //ParameterExpression p2 = Expression.Parameter(typeof(int), "b") ;
                //BinaryExpression binaryExpress = Expression.Multiply(p1, p2);
                //var func = Expression.Lambda<Func<int, int, int>>(binaryExpress, new ParameterExpression[] { p1, p2 }).Compile();
                //MessageBox.Show(func(10, 20).ToString());
    
                //C. Expression.Property(origParam, prop)
                ParameterExpression  p1 = Expression.Parameter(typeof(aa), "a");
                var s = typeof(aa).GetProperties();
                var s1 = s.ToArray()[0];
                MemberExpression member =  Expression.Property(p1, s1.Name) ;
    
                //1
               // var fun = (Func<aa, string>)Expression.Lambda(member, p1).Compile();
    
                //or
                var fun = Expression.Lambda<Func<aa, string>>(member, p1).Compile();
    
                MessageBox.Show(fun(new aa() { test = "abc" }));
                //or
                MessageBox.Show(fun.DynamicInvoke(new aa() { test = "abc" }).ToString());
    
            }
        }
    }
    
  • 相关阅读:
    下拉刷新ListView的实现原理
    自己总结的一些Java公用函数库
    异常处理的最佳实践[转载]
    Android Parcelable和Serializable的区别
    Android BroadcastReceiver介绍
    添加androidsupportv4 错误 java.lang.ClassNotFoundException: android.support.v4.view.ViewPager in loader dalvik.system.PathClassLoader
    [转载]SQL SERVER 数据类型详解
    pthread
    main参数
    实验二测试
  • 原文地址:https://www.cnblogs.com/a_bu/p/6679483.html
Copyright © 2011-2022 走看看