获取匿名对象的属性

记事本 2010-08-04 23:17:54 累计浏览 2,787 次
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. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. C++11的Lambda使用一例:华容道求解 (累计阅读 3,605)
  2. 基于C++ Lambda表达式的程序优化 (累计阅读 2,582)