IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

获取匿名对象的属性

记事本 2010-08-04 23:17:54 累计浏览 2,612 次
本机暂存
以下是代码片段:
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. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

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