匿名对象和object的转换

有时候经常用到需要把一个匿名对象存入session或List<object>或其他容器中,可是取出来的时候变成object了,不太方便使用。

下面是一种转换方式:

    class Program
    {
        static void Main(string[] args)
        {
            List<object> olist = new List<object>();
            olist.Add(new { Name = "Hauk", Age = 22 });
            olist.Add(new { Name = "Emily", Age = 22 });


            //使用动态类型
            foreach (dynamic item in olist)
            {
                Console.WriteLine(item.Name);
            }


            //做类型转换
            var obj = ChangeType(olist[0], new { Name = "", Age = 0 });
            Console.WriteLine(obj.Name);


            //直接反射
            Console.WriteLine(olist[0].GetType().GetProperty("Name").GetValue(olist[0]).ToString());
        }


        static T ChangeType<T>(object obj, T t)
        {
            return (T)obj;
        }
    }

  

原文地址:https://www.cnblogs.com/sntetwt/p/5385185.html