gpt4 book ai didi

c# - 如何显示作为 int[] 数组的 OrderedDictionary 条目值的值?

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:23 25 4
gpt4 key购买 nike

我宁愿不在有序字典中将两个单独的值创建到单独的条目中,但如果有一种方法可以完成我在这里尝试做的事情,那就太棒了。

public OrderedDictionary spellResults = new OrderedDictionary()
{
{"Test",new int[]{5,7}}
};

public void Main()
{
//i'm trying to display the integers within "spellResults["Test"]" but i have no idea how i would accomplish this

int[] pval= ((Array)spellResults["Test"]) as int[];
Console.WriteLine(pval[0]+","+pval[1]);
}

Edit: Turns out the way I was doing it was also correct but I overlooked placing the OrderedDictionary in a class when I was using an online compiler to try and test it for the first time. Whoops, thanks for the answers anyhow.

最佳答案

foreach (var number in spellResults["Test"] as int[])
{
Console.WriteLine(number);
}

但是,您需要先检查 spellResults["Test"] 的类型,因为如果转换为 int[] 将抛出 NullReferenceException 不成功(即它将尝试遍历 null)。您应该事先执行空检查:

var pval = spellResults["Test"] as int[];
if (pval != null)
{
foreach (var number in pval)
{
Console.WriteLine(number);
}
}

要以 CSV 格式打印数字,按照原始片段,只需将 foreach 替换为 string.Join - 这样,您还可以避免程序抛出 IndexOutOfRangeException在运行时,如果 pval 包含少于 2 个元素:

if (pval != null)
{
// this is bad, an IndexOutOfRangeException will be thrown
// if pval contains less than 2 elements:
// Console.WriteLine(pval[0] + "," + pval[1]);

// use string.Join instead::
Console.WriteLine(string.Join(",", pval));
}

关于c# - 如何显示作为 int[] 数组的 OrderedDictionary 条目值的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567117/

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