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();
}
方法中的第一个 _t就是一个类型。
这是核心代码,代码主要实现的功能是 根据属性名称高效的获得值(一般都是用反射,但是反射比较耗),可以简单的讲一下 这一行一行代码是做什么吗?我只知道是利用表达式树。我百度过 代码上的很多关键字,可是还是看不懂。
这段代码产生类似如下的函数
object MyFunc(object instance, string memberName)
{
int nameHash;
nameHash = memberName.GetHashCode();
switch (nameHash)
{
case 1234: // 根据某个属性的Hash值生成1234
return (YYYY)instance.XXXX; // xxxx是属性名,yyyy是属性的类型
...
}
}