当我声明foreach时,编译器会向我显示以下错误:
foreach语句不能对'System.Data.DataTable'类型的变量进行操作,因为'System.Data.DataTable'不包含'GetEnumerator
的公共定义
这是代码:
leagueTable_link = item.Links.LeagueTable.href.ToString();
object leagueTable_object = load_League_Table(leagueTable_link);
foreach (var classifica in leagueTable_object)
{
}
这是由在线工具Json2C#:
创建的类using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class LeagueTable
{
public string[] _links = new string[50];
public int[] position = new int[50];
public string[] teamName = new string[50];
public int[] playedGames = new int[50];
public int[] points = new int[50];
public int[] goals = new int[50];
public int[] goalsAgainst = new int[50];
public int[] goalDifference = new int[50];
public struct League_Struct
{
public string _links;
public int position;
public string teamName;
public int playedGames;
public int points;
public int goals;
public int goalsAgainst;
public int goalDifference;
}
public League_Struct[] league_struct = new League_Struct[50];
public class Links
{
public string self { get; set; }
public string soccerseason { get; set; }
}
public class Team
{
public string href { get; set; }
}
public class Links2
{
public Team team { get; set; }
}
public class Standing
{
public Links2 _links { get; set; }
public int position { get; set; }
public string teamName { get; set; }
public int playedGames { get; set; }
public int points { get; set; }
public int goals { get; set; }
public int goalsAgainst { get; set; }
public int goalDifference { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public string leagueCaption { get; set; }
public int matchday { get; set; }
public List<Standing> standing { get; set; }
}
}
}
leagueTable_object包含这个:
var obj = JsonConvert.DeserializeObject<LeagueTable.RootObject>(responseText);
我该如何解决这个问题?我看到网上不同的解决方案,但我不明白。我应该在我的Json类中实现GetEnumerator类吗?
答案 0 :(得分:1)
您的leagueTable_object对象的类型似乎是&#39; System.Data.DataTable&#39;这不是可枚举的类型,因此您无法循环此对象。 您可以做的是循环此DataTable中的行:
leagueTable_link = item.Links.LeagueTable.href.ToString();
DataTable leagueTable_object = load_League_Table(leagueTable_link);
foreach (var classifica in leagueTable_object.Rows)
{
}
答案 1 :(得分:0)
看起来leagueTable_object是DataTable的一个对象。如果它是一个列表,那么它将起作用。
Foreach可以用于继承IEnumerable的类。您可以在foreach中使用leagueTable_object.Rows
而不是leagueTable_object
。
答案 2 :(得分:0)
如果您的对象是DataTable
类型,那么问题在于您尝试迭代DataTable
对象,而您需要迭代其行。因此,请尝试将foreach
代码更改为此类代码。
foreach (var classifica in leagueTable_object.Rows)
{
}
您也可以leagueTable_object
直接投放DataTable
而不是使用object
。这将使观众更清楚,因为他知道创建了哪种类型的对象。
希望这有帮助。