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

C#中IEnumerable<T>泛型方法返回字符串触发类型转换错误如何解决

问题核心错误

  • 逻辑错误:你调用的Distinct()是全局去重,题目要求仅去除连续重复的元素,两者逻辑完全不符。
  • 类型判断错误:当输入为字符串时,输入的实际类型是IEnumerable<char>,泛型参数T为char,你判断typeof(T) == typeof(string)的逻辑永远不会命中。
  • 返回值类型错误:返回数组或手动强制转字符串都会触发类型不匹配错误。

正确实现方案

使用迭代器遍历序列,仅返回和前一个元素不相等的元素,天然适配泛型返回值要求:

public static class Kata
{
    public static IEnumerable<T> UniqueInOrder<T>(IEnumerable<T> arr) 
    {
        if (arr == null) yield break;
        bool isFirstElement = true;
        T lastElement = default;
        
        foreach (T current in arr)
        {
            if (isFirstElement)
            {
                isFirstElement = false;
                lastElement = current;
                yield return current;
            }
            else if (!EqualityComparer<T>.Default.Equals(current, lastElement))
            {
                lastElement = current;
                yield return current;
            }
        }
    }
}

实现说明

  1. 用yield return返回迭代器,天然符合IEnumerable<T>的返回值要求,不需要手动做任何类型转换。
  2. 用EqualityComparer<T>.Default.Equals做相等判断,兼容所有泛型类型的比较逻辑,不需要单独判断类型分支。
  3. 逻辑上仅过滤连续重复的元素,输入"AAAABBBCCDAABBB"时返回的IEnumerable<char>序列正好对应"ABCDAB"的每个字符,测试框架会自动匹配字符串对比,不会出现类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:39:02