dynamic 牛刀小试

今天在网上看帖时看到了这样一个问题:

现在我用反射“PersonModel.dll",调用一个类型方法:GetAllPersons(),返回Person[],其中Person为“PersonModel.dll"在定义,请问,我要怎么操作才能取回返回的数组值呢?

http://topic.csdn.net/u/20120705/10/7f596ac7-d409-45a1-afe0-c12177c3432d.html?seed=1764403403&r=79038805#r_79038805

恰好手头没事做,就顺手写了一个Demo,但在获取到结果遍历时发现代码量太大了,

突然记起来在4.0版本中还有个dynamic类型,用起来还非常方便,能像以前一样直接遍历并取值,

实在是太方便了,不说废话了,上代码吧

PersonModel.dll:

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace PersonModel
 7 {
 8     public class Class1
 9     {
10 
11         public Person[] GetAllPersons()
12         {
13             Person[] p = new Person[]
14             {
15             new Person(){Name="aaa",Age=20},
16             new Person(){Name="bbb",Age=21},
17             new Person(){Name="ccc",Age=26}
18             };
19             return p;
20         }
21     }
22     public class Person
23     {
24         public string Name { get; set; }
25 
26         public int Age { get; set; }
27     }
28 }

 

 

测试类:

 

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Reflection;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "PersonModel.dll");
14             object instance = assembly.CreateInstance("PersonModel.Class1");
15             MethodInfo method = instance.GetType().GetMethod("GetAllPersons");
16             Array result = (Array)method.Invoke(instance, null);
17             //直接用dynamic遍历结果就行了
18             foreach (dynamic item in result)
19             {                
20                 Console.WriteLine(item.Name + "  " + item.Age);
21             }
22 23 24 Console.Read(); 25 } 26 27 28 } 29 }

 

输出:

aaa 20
bbb 21
ccc 26

 

补充:

dynamic(C# 参考)

http://msdn.microsoft.com/zh-cn/library/dd264741.aspx

在通过 dynamic 类型实现的操作中,该类型的作用是绕过编译时类型检查, 改为在运行时解析这些操作。 dynamic 类型简化了对 COM API(例如 Office Automation API)、动态 API(例如 IronPython 库)和 HTML 文档对象模型 (DOM) 的访问。

在大多数情况下,dynamic 类型与 object 类型的行为是一样的。 但是,不会用编译器对包含 dynamic 类型表达式的操作进行解析或类型检查。 编译器将有关该操作信息打包在一起,并且该信息以后用于计算运行时操作。 在此过程中,类型 dynamic 的变量会编译到类型 object 的变量中。 因此,类型 dynamic 只在编译时存在,在运行时则不存在。

 

总结:

这样是不是非常方便呢?

有时候我们总是陷入思想怪圈里而不可自拔,需要不断学习应用新技术,打破思维惯性才能不断进步。

posted @ 2012-07-05 14:22  ludard  阅读(2739)  评论(25编辑  收藏  举报