码迷,mamicode.com
首页 > Windows程序 > 详细

C# 表达式树学习笔记

时间:2017-04-07 20:24:57      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:com   array   sap   http   form   动态表   示例   orm   .property   

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

        }
    }
}

 

C# 表达式树学习笔记

标签:com   array   sap   http   form   动态表   示例   orm   .property   

原文地址:http://www.cnblogs.com/a_bu/p/6679483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!