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());

        }
    }
}

 

 posted on 2017-04-07 18:21  仰光  阅读(309)  评论(0编辑  收藏  举报