标签:style blog http ar color os 使用 sp for
不知道从.NET几点几开始有个这2个关键字,但是的确可以减少一些编程代码量,性能也还未知,仅记录对比2种不同的编码,得到相同的效果:
一、使用一般的编码:
先来3个Model类:
1 public class NMenus 2 { 3 public List<MTitle> titles { get; set; } 4 5 public NMenus() 6 { 7 titles = new List<MTitle>(); 8 } 9 } 10 11 public class MTitle 12 { 13 public int tid { get; set; } 14 public string tname { get; set; } 15 public string ticon { get; set; } 16 17 public List<MTItem> items { get; set; } 18 19 public MTitle() 20 { 21 items = new List<MTItem>(); 22 } 23 } 24 25 public class MTItem 26 { 27 public int iid { get; set; } 28 public string iname { get; set; } 29 public string iicon { get; set; } 30 public string iurl { get; set; } 31 }
再来看筛选并转JSON的代码:
1 NMenus menus = new NMenus(); 2 foreach (SysNavMenu title in titles) 3 { 4 var items = from m in menusList 5 where m.PMId == title.MId 6 select new MTItem { iid = m.MId, iname = m.MText, iicon = m.Icon, iurl = m.MUrl }; 7 var t = new MTitle { tid = title.MId, tname = title.MText, ticon = title.Icon, items = items.ToList<MTItem>() }; 8 menus.titles.Add(t); 9 } 10 jsonMenus = JsonConvert.SerializeObject(menus);
二、使用var和dynamic的编码:
1 var menus = new { titles = new List<dynamic>() }; 2 foreach (SysNavMenu title in titles) 3 { 4 var items = from m in menusList 5 where m.PMId == title.MId 6 select new { iid = m.MId, iname = m.MText, iicon = m.Icon, iurl = m.MUrl }; 7 var t = new { tid = title.MId, tname = title.MText, ticon = title.Icon, items = items.ToList<dynamic>() }; 8 menus.titles.Add(t); 9 } 10 jsonMenus = JsonConvert.SerializeObject(menus);
小结:一和二得到的最终jsonMenus字符串是相同的,唯一不同的就只有......
标签:style blog http ar color os 使用 sp for
原文地址:http://www.cnblogs.com/williamlyf/p/4161188.html