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

C#中Json<TK,TV>无法用集合初始化器?报错未实现IEnumerable

问题原因及解决方案

错误原因

你的Json<TK, TV>类虽然定义了GetEnumerator方法,但没有显式实现System.Collections.IEnumerable接口。C#编译器要求类必须实现该接口(或其泛型派生接口),才能支持集合初始化语法——哪怕你已经具备了Add方法和枚举器方法,编译器也需要明确的接口实现来识别这是一个可枚举集合类型。

修复方案

在类声明处添加接口实现,推荐实现泛型的IEnumerable<KeyValuePair<TK, TV>>(它继承自非泛型IEnumerable,同时提供强类型枚举支持),并完善接口的实现代码:

修改后的完整代码

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

// 建议使用自定义命名空间,避免与System命名空间冲突
namespace YourCustomNamespace
{
    class Json<TK, TV> : IEnumerable<KeyValuePair<TK, TV>>
    {
        public Dictionary<TK, TV> _dictionary;

        public Json()
        {
            _dictionary = new Dictionary<TK, TV>();
        }

        public Json(Dictionary<TK, TV> dictionary)
        {
            _dictionary = dictionary;
        }

        public void Add(TK key, TV value)
        {
            _dictionary.Add(key, value);
        }

        // 实现泛型接口的GetEnumerator
        public IEnumerator<KeyValuePair<TK, TV>> GetEnumerator()
        {
            return _dictionary.GetEnumerator();
        }

        // 显式实现非泛型IEnumerable的GetEnumerator,满足接口继承要求
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public TV this[TK key]
        {
            get => _dictionary[key];
            set => _dictionary[key] = value;
        }
    }
}

关键说明

  • 集合初始化器的生效条件:类需实现IEnumerable(或泛型版本),且包含与初始化元素匹配的Add方法。你的类已有Add(TK key, TV value),满足元素配对的初始化需求,补上接口实现即可解决错误。
  • 使用泛型IEnumerable<KeyValuePair<TK, TV>>而非非泛型IEnumerable,能避免值类型的装箱拆箱操作,同时提供更安全的类型检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:10:04