gpt4 book ai didi

c# - 如何将动态字典值转换为列表?

转载 作者:行者123 更新时间:2023-11-30 15:03:37 25 4
gpt4 key购买 nike

我有以下代码:

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()); 时,出现以下异常

Public member 'ToList' on type 'ValueCollection' not found.

堆栈跟踪:

   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());

最佳答案

只是施放它:

list.AddRange(((IEnumerable<string>)dic1.Values).ToList());

此外,您可以再次通过动态:

list.AddRange((dynamic)dic1.Values));

关于c# - 如何将动态字典值转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11342477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com