我有下面的代碼:我如何將動態字典值轉換爲列表?
List<Type> p1 = new List<Type>();
p1.Add(typeof(int));
p1.Add(typeof(string));
dynamic genericDic = typeof(Dictionary<, >);
dynamic specificDic1 = genericDic.MakeGenericType(p1.ToArray());
dynamic dic1 = Activator.CreateInstance(specificDic1);
dic1.Add(1, "John");
dic1.Add(2, "Smith");
dynamic genericLst = typeof(List<>);
dynamic specificLst = genericLst.MakeGenericType(typeof(string));
dynamic list = Activator.CreateInstance(specificLst);
list.AddRange(dic1.Values.ToList());
當我嘗試執行list.AddRange(dic1.Values.ToList());
我得到下面的異常
公共成員「ToList」上鍵入'ValueCollection找不到。
堆棧跟蹤:
at Microsoft.VisualBasic.CompilerServices.Symbols.Container.GetMembers(String& MemberName, Boolean ReportErrors)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at StyleResearch.DataManagement.DataStream.Business.MonthEndProcess.ConverToLegacyStructureInMemory(List`1 marketDataTypeIds, String tableName, Int32 placeHolderValue) in C:\Style Research\Work\SRDM\trunk\StyleResearch.DataManagement.DataStream.Business\MonthEndProcess.vb:line 1850
at StyleResearch.DataManagement.DataStream.UI.DDLMonthEndProcess._Lambda$__6(LegacyStructureDetail legacy) in C:\Style Research\Work\SRDM\trunk\StyleResearch.DataManagement.DataStream.UI\DDLMonthEndProcess.vb:line 1198
at System.Threading.Tasks.Parallel.<>c__DisplayClass2d`2.<ForEachWorker>b__23(Int32 i)
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
注:我已經VB.NET樣品轉化成C#,但堆棧跟蹤從VB.NET工程
當我做下面的工作原理精絕:
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "John");
dic.Add(2, "Smith");
List<string> lst = new List<string>();
lst.AddRange(dic.Values.ToList());
感謝您的回覆,但我確實知道這種方法。想知道爲什麼它會失敗時,我使用反射創建對象,而不是正常進行時。 – Rajesh 2012-07-05 10:44:18
正如我所說的那樣,因爲動態類型和擴展方法(ToList)。動態不支持擴展方法(http://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object-in-c-sharp) – Nikolay 2012-07-05 10:46:39