首页 > 代码库 > 使用Expression tree访问类的属性名称与值
使用Expression tree访问类的属性名称与值
表达式树Expression是Linq中一项比较重要的功能,对其深刻了解Lamda以及计算表达式有很大的帮助.
下面是利用 Expression<Func<Object>>[]取得Func<Object>中的操作数或成员名称以及值。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Linq.Expressions;using System.Reflection;namespace ExpressionTree{ class Program { static void Main(string[] args) { MyClass cls = new MyClass() { Memo = "ffffddddd", Name = "dfdf", Age = 33 }; Dictionary<string, string> dic = GetProps(() => cls.Memo, () => cls.Age); foreach (KeyValuePair<string,string> item in dic) { Console.WriteLine(item.Key + "=" + item.Value); } Console.Read(); } static Dictionary<string, string> GetProps(params Expression<Func<Object>>[] funcs) { Dictionary<string, string> dic = new Dictionary<string, string>(); MemberExpression member = null; UnaryExpression unary = null; foreach (Expression<Func<Object>> func in funcs) { unary = func.Body as UnaryExpression; if (unary != null) { member = unary.Operand as MemberExpression; } else { member = func.Body as MemberExpression; } PropertyInfo prop = member.Member as PropertyInfo; object value =http://www.mamicode.com/ func.Compile().Invoke(); dic.Add(prop.Name, Convert.ToString(value)); } return dic; } } class MyClass { public string Name { get; set; } public int Age { get; set; } public string Memo { get; set; } }}
使用Expression tree访问类的属性名称与值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。