我有以下代码:
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());
时,我得到以下异常
未找到类型'ValueCollection'上的公共成员'ToList'。
堆栈追踪:
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());
答案 0 :(得分:3)
投下它:
list.AddRange(((IEnumerable<string>)dic1.Values).ToList());
此外,您可以再次通过动态:
list.AddRange((dynamic)dic1.Values));
答案 1 :(得分:2)
ToList&lt; T&gt;()是IEnumerable&lt; T&gt;的扩展方法。但你的dic1.Values是动态类型而不是IENumerable&lt; string&gt;所以.Net找不到并使用这种扩展方法。你可以尝试简单的foreach:
foreach (var value in dic1.Values)
list.Add(value)
答案 2 :(得分:0)
list.AddRange((IEnumerable<string>)dic.Values))
或
List<string> list = ((IEnumerable<string>)dic.Values).ToList();
或
List<string> list = new List<string>((IEnumerable<string>)dic.Values);
答案 3 :(得分:0)
尝试使用无扩展函数语法进行调用,例如
Enumerable.ToList ( (dynamic) dic1.Values )
DLR不会在运行时搜索继承接口的扩展功能(出于性能原因或避免含糊不清,我猜)。