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

标签 c# dictionary unity3d

我正在尝试在 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/

相关文章:

unity3d - 带有 native 库的 HoloLens 回调

c# - 如何使用自动映射器将具有多对多关系的 DTO 映射到具有关系表的 EF 核心实体?

c# - 有没有办法否定谓词?

c# - 有没有一种方法可以使用 JsonConverter 派生的自定义转换器进行依赖注入(inject)

python - 在 python 中进行对应替换操作的更快方法?

c# - Unity 3d 中的嵌套列表 - 我该怎么做?

c# - 如何存储和序列化列表以避免长字符串

c# - 需要了解如何处理 Winforms 应用程序中的可变任务组

swift - 如何检查字典中的值?

arrays - 使用元组通过映射分配数组值时参数过多