为要在foreach中使用的ITuple类型对象实现GetEnumerator

问题描述

所以我不得不重构一些代码,现在我试图迭代一些ITuple对象,并将它们添加到列表中,如下所示。

       //for the case when we have an object of type IList this works
            if (obj is IList) {
            var list = new List<GuiValue>();
            foreach (var o in (IList)obj) {
                list.Add(MethodResultToGuiValue(o));
            }
            return new GuiValue.GV_list(list);
        }
        // this is what I'm interested to solve
        if (obj is ITuple) {
            var list = new List<GuiValue>();
            foreach (var o in (ITuple)obj) {
                list.Add(MethodResultToGuiValue(o));
            }
            return new GuiValue.GV_tuple(list);
        }

所以我遇到的问题很明显:

enter image description here

类型'System.Runtime.CompilerServices.ITuple'不能在'foreach'语句中使用,因为既没有实现'IEnumerable'的'IEnumerable',也没有合适的'GetEnumerator'方法,返回类型具有'Current'属性和'移动”方法

我严格按照建议进行操作,创建了一个新的TupleExtensions.cs类, 并为此做了扩展方法

internal static class TupleExtensions {

    internal static IEnumerable GetEnumerator(this ITuple tuple) {
        return tuple.GetType()
            .GetProperties()
            .Select(property => property.GetValue(tuple));
    }
}

但是我仍然遇到上述错误

解决方法

如果您想通过ItemX属性进行“迭代”,则不能只是

foreach (var o in (ITuple)obj)

因为ITuple未实现IEnumerable。但是,您可以执行以下操作

if (obj is ITuple tuple) // Minor improvement to keep the result of the cast
{
   // .....
   foreach (var o in tuple.GetEnumerator()) // Explicitly get the IEnumerable
   {
     // ......
   }
   // rest of your code
}