dynamic关键字才出来的时候,以为真是没什么用,谁老是和com交互来交互去啊,惟恐避之不及啊。性能
后来逐渐算是有了一些使用心得,发现这货还真是犀利啊,故在此举几个例子,起抛砖引玉之用。ui
1.替代XXX.GetType().GetProperty("YYY").GetValue(XXX)spa
static object GetPerson() { return new Person { Name = "Leo" }; }
有时候不免会遇到这种返回object的倒霉代码(特别是跟反射有关的时候),这时咱们又要访问其中的某个属性,那个费劲啊,如今有了dynamic感受好多了。pwa
object objPerson = GetPerson(); var objName = objPerson.GetType().GetProperty("Name").GetValue(objPerson); Console.WriteLine(objName); dynamic dynPerson = GetPerson(); var dynName = dynPerson.Name; Console.WriteLine(dynName);
另外一个好处是性能会获得一程度的提高:设计
Watch = new Stopwatch(); Watch.Start(); for (int i = 0; i < 1000000; i++) { objName = objPerson.GetType().GetProperty("Name").GetValue(objPerson); } Watch.Stop(); Console.WriteLine(Watch.Elapsed); Watch.Restart(); for (int i = 0; i < 1000000; i++) { dynName = dynPerson.Name; } Watch.Stop(); Console.WriteLine(Watch.Elapsed);
大体结果以下图,仍是快了不少的:code
2.拯救接手接口没设计好的代码的倒霉孩子对象
好比这里有N个WCF服务,返回了N个对象的集合,这几个对象没啥关系,其实又有一点关系,倒霉孩子又不会让Entity Framework生成的类自动继承某个接口(本文里用本地方法代替WCF服务)。blog
这里来举一个例子,首先有下面2个倒霉的类,一样string类型的name是能够提取接口的(这里真的合适提取么……),一样名称但不一样类型的ID,彻底无关的Age和Price。继承
public class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public static List<Person> GetPersonList() { return new List<Person> { new Person{ Name = "Leo1" , Age = 10 }, new Person{ Name = "Leo2" , Age = 20 }, new Person{ Name = "Leo3" , Age= 30 } }; } } public class Car { public Guid ID { get; set; } public string Name { get; set; } public double Price { get; set; } public static List<Car> GetCarList() { return new List<Car> { new Car{ Name = "Focus1" , Price = 100 }, new Car{ Name = "Focus2" , Price = 200 }, new Car{ Name = "Focus3" , Price = 300 } }; } }
我用2个static方法返回不一样类型的List<T>来模拟WCF中最普通的调用。接口
static void Main(string[] args) { List<dynamic> list = new List<dynamic>(); //用本地方法替代WCF服务,您伪装是经过WCF获取的list Person.GetPersonList().ForEach((p) => list.Add(p)); TestDynamic2(list,"Leo2"); list = new List<dynamic>(); //用本地方法替代WCF服务,您伪装是经过WCF获取的list Car.GetCarList().ForEach((c) => list.Add(c)); TestDynamic2(list,"Focus3"); Console.ReadKey(); } private static void TestDynamic2(List<dynamic> list,string name) { //能够无差异的使用ID和Name属性 dynamic first = list.OrderBy(d => d.ID).FirstOrDefault(d => d.Name.Contains(name)); //差异对待不一样的属性,这里供参考,不建议这么写,这会致使依赖具体的类型 if (first is Person) { Console.WriteLine(first.Age); } else { Console.WriteLine(first.Price); } }
本文提供了使用dynamic的一点心得,若是有不对的对方,还望各位不吝指出,很是感谢!