private Func<object, string, object> GenerateGetValue() { var type = _t; var instance = Expression.Parameter(typeof(object), "instance"); var memberName = Expression.Parameter(typeof(string), "memberName"); var nameHash = Expression.Variable(typeof(int), "nameHash"); var calHash = Expression.Assign(nameHash, Expression.Call(memberName, typeof(object).GetMethod("GetHashCode"))); var cases = new List<SwitchCase>(); foreach (var propertyInfo in type.GetProperties()) { var property = Expression.Property(Expression.Convert(instance, type), propertyInfo.Name); var propertyHash = Expression.Constant(propertyInfo.Name.GetHashCode(), typeof(int)); cases.Add(Expression.SwitchCase(Expression.Convert(property, typeof(object)),propertyHash)); } var switchEx = Expression.Switch(nameHash, Expression.Constant(null), cases.ToArray()); var methodBody = Expression.Block(typeof(object), new[] { nameHash }, calHash, switchEx); return Expression.Lambda<Func<object, string, object>>(methodBody, instance, memberName).Compile(); }
这是一段代码的核心逻辑,主要实现了 <传一个类型和一个属性名称,可以高效的获得 属性值> 这个功能。我断点看了好多遍,也把各个关键字百度搜索了下,可是还是看不懂。只知道这是利用表达式树 = =!哪个大神可以简单的讲解下,这一行一行代码到底在做什么。或者告诉我下,要读懂这代码 ,需要什么预备知识,如果大神们如果曾经看到过相关的博客,也可以给下我。
目的好像是动态创建表达式树,能力有限,我也看不太懂
以及http://www.cnblogs.com/ldp615/archive/2011/09/15/expression-extension-methods.html
更多资料请自己查询