今天在網上看帖時看到了這樣一個問題:
現在我用反射“PersonModel.dll",調用一個類型方法:GetAllPersons(),返回Person[],其中Person為“PersonModel.dll"在定義,請問,我要怎么操作才能取回返回的數組值呢?
恰好手頭沒事做,就順手寫了一個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 只在編譯時存在,在運行時則不存在。
總結:
這樣是不是非常方便呢?
有時候我們總是陷入思想怪圈里而不可自拔,需要不斷學習應用新技術,打破思維慣性才能不斷進步。