技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> 获取匿名对象的属性

获取匿名对象的属性

浏览:1713次  出处信息

以下是代码片段:
namespace System.Extension.Dynamic
{
    public static class Dynamic
    {
        private static Dictionary<PropertyInfo, object> propertyGetters = new Dictionary<PropertyInfo, object>();
        public static object Property(this object instance, string name)
        {
            var instanceType = instance.GetType();
            var propertyInfo = instanceType.GetProperty(name);
            if (propertyInfo == null) throw new InvalidOperationException();
            if (!propertyInfo.CanRead) throw new InvalidOperationException();
            object compiled;
            if (!propertyGetters.TryGetValue(propertyInfo, out compiled))
            {
                var parameter = Expression.Parameter(typeof(object), "obj");
                var convertParameter = Expression.Convert(parameter, instance.GetType());
                var property = Expression.Property(convertParameter, propertyInfo);
                var convertReturnValue = Expression.Convert(property, typeof(object));
                var lambda = Expression.Lambda(convertReturnValue, parameter);
                compiled = lambda.Compile();
                propertyGetters.Add(propertyInfo, compiled);
            }
            return ((Func<object, object>)compiled)(instance);
        }
    }
}

建议继续学习:

  1. 前端必须熟悉的10个CSS3属性    (阅读:2842)
  2. 细说JavaScript中对象的属性和方法    (阅读:1807)
  3. [Perl6]类, 属性, 方法和其它    (阅读:1415)
  4. 细说魅力属性    (阅读:1244)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1