无法转换类型' InternationalRowViewDetailsModel'输入' System.Collections.IEnumerator'

时间:2017-01-16 22:04:42

标签: c# ienumerable ienumerator

我有一个课程如下:

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

namespace DataBinding.Schemas.Scenario.ViewModels
{
    public class InternationalRowViewDetailsModel: IEnumerable
    {
        public InternationalRowViewDetailsModel()
        {
            Country = new System.Collections.Generic.Dictionary<object, object>();
            RateEUR = new System.Collections.Generic.Dictionary<object, object>();
            RateGBP = new System.Collections.Generic.Dictionary<object, object>();
            RateUSD = new System.Collections.Generic.Dictionary<object, object>();
        }

        public Dictionary<object, object> Country { get; set; }
        public Dictionary<object, object> RateEUR { get; set; }
        public Dictionary<object, object> RateGBP { get; set; }
        public Dictionary<object, object> RateUSD { get; set; }

        public IEnumerator GetEnumerator() { return (IEnumerator)this; }
    }
}

现在我试图按如下方式遍历InternationalRowViewDetailsModel的值:

foreach (InternationalRowViewDetailsModel currentRow in viewModel)
{
   Row newRow = FillInternationalNumberRow(itemRow, currentRow);
   tableNode.Rows.Add(newRow);
}

我想使用foreach并将每个当前行发送到填充表格列的方法FillInternationalNumberRow。

 private static Row FillInternationalNumberRow(Row rowTemplate, InternationalRowViewDetailsModel internationalViewModel)
        {
            Row newRow = rowTemplate.Clone(true) as Row;
            int currentCell = 0;
            if (newRow != null)
            {
                newRow.Cells[currentCell++].FirstParagraph.Runs[0].Text = internationalViewModel.Country.ToString();
                newRow.Cells[currentCell++].FirstParagraph.Runs[0].Text = internationalViewModel.RateEUR.ToString();
                newRow.Cells[currentCell++].FirstParagraph.Runs[0].Text = internationalViewModel.RateGBP.ToString();
                newRow.Cells[currentCell++].FirstParagraph.Runs[0].Text = internationalViewModel.RateUSD.ToString();
            }
            return newRow;
        }

但是我收到以下错误: 无法转换类型为&#39; DataBinding.Schemas.Scenario.ViewModels.InternationalRowViewDetailsModel&#39;的对象输入&#39; System.Collections.IEnumerator&#39;

2 个答案:

答案 0 :(得分:2)

您的班级实施IEnumerable

public class InternationalRowViewDetailsModel: IEnumerable

然而,您正试图将其投射为IEnumerator

public IEnumerator GetEnumerator() { return (IEnumerator)this; }

您要迭代的对象也必须实现IEnumerator,以便代码知道如何遍历您的集合。

答案 1 :(得分:0)

您没有正确实现界面。这是一个实现IEnumerable

的类型
public class A : IEnumerable {
   private List<string> items = new List<string>();

   public IEnumerator GetEnumerator() {
      return this.items.GetEnumerator();
   }
}

在上面的代码中,我只是返回内部列表的IEnumerator

请谨记使用IEnumerable时,会产生Object类型的项目。所以即使在上面我有一个List<string>,当遍历它时,它将返回类型Object。如果可能,尝试使用通用的IEnumerable<T>来避免装箱和拆箱。