匿名对象和object的转换

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

下面是一种转换方式:
[csharp] 
    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;  
        }  
    }  
 
 
举例:

@foreach (dynamic item in ViewBag.AAA)
{

<div>@item.GetType().GetProperty("Title").GetValue(item)</div>
foreach (var cond in item.GetType().GetProperty("NovelCharpter").GetValue(item))
{
<div>@cond.GetType().GetProperty("Name").GetValue(cond)</div>
}
}

ViewBag.AAA = (from i in db.Novel.Take(10).AsEnumerable()
select new
{
i.ID,
i.Title,
i.Author,
NovelCharpter = from m in i.NovelCharpter
select new {
m.ID,
m.Name
}
}).ToList();

原文地址:https://www.cnblogs.com/tianxiang2046/p/3586537.html