【问题标题】:Implement GetEnumerator for ITuple type objects to be used in foreach为要在 foreach 中使用的 ITuple 类型对象实现 GetEnumerator
【发布时间】:2020-12-22 09:08:30
【问题描述】:

所以我不得不重构一些代码,现在我正在尝试迭代一些 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);
        }

所以我的问题很清楚:

类型'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));
    }
}

但我仍然收到上述错误。

【问题讨论】:

  • “正是它的建议” - 不,你实现了一个扩展方法。消息中没有任何部分表明可以在此处使用扩展方法。
  • 是的,@Damien_The_Unbeliever 我认为这是解决问题的一种方法。我还能如何使用“GetEnumerator”方法?

标签: c# foreach tuples ienumerable


【解决方案1】:

如果你想“迭代”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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2012-04-15
    • 2014-01-09
    • 2021-06-21
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多