- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace LinqTestConsole
- {
- class Program
- {
- static void Main(string[] args)
- {
- List<Object> lo = new List<object>();
- for (int i = 0; i <1500000; i++) {
- Object o = new { name = "name" + i, age = i };
- lo.Add(o);
- }
- DateTime dt10= DateTime.Now;
- //通过dynamic取值
- foreach(dynamic o in lo){
- string s = o.name + "的年龄是:" + o.age + "岁";
- }
- DateTime dt11 = DateTime.Now;
- TimeSpan span = dt11.Subtract(dt10);
- Console.WriteLine("用时"+ span.Minutes + "分钟" + span.Seconds + "秒"+span.Milliseconds+"毫秒");
- //通过反射取值
- foreach (Object o in lo)
- {
- string s=GetPropertyValueByName("name", o).ToString() + "的年龄是:" + GetPropertyValueByName("age", o).ToString() + "岁";
- }
- DateTime dt22 = DateTime.Now;
- span = dt22.Subtract(dt11);
- Console.WriteLine("用时" + +span.Minutes + "分钟" + span.Seconds + "秒" + span.Milliseconds + "毫秒");
- Console.Read();
- }
- /// <summary>
- /// 反射,通过属性名称,取值
- /// </summary>
- /// <param name="PropertyName"></param>
- /// <param name="o"></param>
- /// <returns></returns>
- public static Object GetPropertyValueByName(string PropertyName, Object o)
- {
- if (o == null)
- {
- o = new { };
- }
- //创建一个返回对象
- Object returnObject = new Object();
- PropertyInfo[] p1 = o.GetType().GetProperties();
- foreach (PropertyInfo pi in p1)
- {
- if (pi.Name.ToLower() == PropertyName.ToLower())
- {
- returnObject = pi.GetValue(o);
- }
- }
- return returnObject;
- }
- }
- }
运行结果:
总结:
从上面可以看出,反射是有点慢的,以后还是尽量用dynamic吧,方便实用。
我比较的方式可能不是很正确,但是,这样的结果也在一定程度上反映了一些问题。