You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity遍历自定义Result对象内列表时出现GetEnumerator错误

解决自定义Result类无法被foreach遍历的问题

你的报错原因很明确:foreach循环要求目标类型要么实现IEnumerable/IEnumerable<T>接口,要么提供一个公共的GetEnumerator()实例方法。你的Result类既没实现接口,也没定义这个方法,所以无法直接用foreach (var item in this)遍历。

下面给两种可行的解决方案:

方案1:直接遍历内部的元组列表(最简单)

不需要修改Result类的结构,直接在getList方法里遍历你存储元组的列表字段/属性即可。假设你的列表属性叫TupleList,代码示例:

public class Result
{
    // 假设这是你存储元组的列表
    public List<(int, int, int)> TupleList { get; set; } = new List<(int, int, int)>();

    public void GetList()
    {
        // 直接遍历内部列表,而非this
        foreach (var item in TupleList)
        {
            // 在这里处理每个元组项,比如打印或逻辑处理
            Debug.Log($"Item: {item.Item1}, {item.Item2}, {item.Item3}");
        }
    }
}

方案2:让Result类实现泛型枚举接口(支持直接遍历this)

如果你希望Result类本身可以像集合一样被foreach遍历,让它实现IEnumerable<(int, int, int)>接口即可,只需实现接口要求的枚举器方法,内部直接复用列表的枚举器:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Result : IEnumerable<(int, int, int)>
{
    public List<(int, int, int)> TupleList { get; set; } = new List<(int, int, int)>();

    // 实现泛型枚举器方法
    public IEnumerator<(int, int, int)> GetEnumerator()
    {
        return TupleList.GetEnumerator();
    }

    // 必须实现的非泛型版本(接口要求)
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void GetList()
    {
        // 现在可以直接遍历this了
        foreach (var item in this)
        {
            Debug.Log($"Item: {item.Item1}, {item.Item2}, {item.Item3}");
        }
    }
}

选择哪种方案取决于你的需求:如果只是单次遍历需求,方案1足够轻便;如果需要Result类具备集合的遍历特性,方案2更合适。

内容的提问来源于stack exchange,提问作者RishtarCode47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:45:32