gpt4 book ai didi

c# - unity3d 字典的无效转换异常

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

我正在尝试在 visual studio 中将字典函数中的随机条目实现到 unity3d 中:Random entry from dictionary .

private void somefunction() {

Dictionary<string, Sprite> dict = (Dictionary<string, Sprite>) RandomValues(slotImages).Take(5);

foreach (KeyValuePair<string, Sprite> keyValue in dict)
{
Debug.Log("random slotImages name : " + keyValue.Key);
}

}
public IEnumerable<TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict)
{
System.Random rand = new System.Random();
List<TValue> values = Enumerable.ToList(dict.Values);
int size = dict.Count;
while (true)
{
yield return values[rand.Next(size)];
}
}

但是我有以下错误;

InvalidCastException: cannot cast from source type to destination type.

最佳答案

您当前在 RandomValues 中的代码返回字典中的随机值列表,而不是实际的字典条目,即键/值对。本质上,您正在尝试将 IEnumerable 转换为 Dictionary,这不能隐式完成。

下面的代码应该做你想做的:

public IDictionary<TKey, TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict, int count)
{
if (count > dict.Count || count < 1) throw new ArgumentException("Invalid value for count: " + count);

Random rand = new Random();

Dictionary<TKey, TValue> randDict = new Dictionary<TKey, TValue>();
do
{
int index = rand.Next(0, dict.Count);
if (!randDict.ContainsKey(dict.ElementAt(index).Key))
randDict.Add(dict.ElementAt(index).Key, dict.ElementAt(index).Value);
} while (randDict.Count < count);

return randDict;
}

请注意,您现在需要将您想要的条目数作为参数传递。返回值将是一个字典,其中包含 count 个随机的、唯一的原始条目。

关于c# - unity3d 字典的无效转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094993/

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