C# 表达式树学习笔记

时间:2022-02-17 07:50:02

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> /// 示例地址: /// </summary> /// <param></param> /// <param></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()); } } }