针对填充列表的C#foreach返回null

时间:2014-09-18 09:00:36

标签: c# foreach xamarin.android

经过一些重大的重构(转向PCL)我有一些代码(不是重构的一部分)运行正常,但现在抛出异常。

该代码是Xamarin Android项目的一部分,该项目在移动到可移植类库之前使用文件链接。

这是一件简单的事情,但我不明白为什么会发生这种情况

foreach(var station in stationList)
{

    // Breakpoint on next line shows station to be null..!
    if(station.ClusterId != Guid.Empty)
    {
        // Code in here
    }
}

问题在于虽然stationList包含许多StationViewModel个对象,但station实例始终为空 - 这怎么可能?

我尝试用foreach循环替换for,但结果相同 - station为空。

我还重新启动了Visual Studio并重新启动。

没有Xamarin更新似乎很出色。

代码运行正常,stationList的生成没有改变,也没有实现这个类。

修改stationList创建过程是:

  1. 在PCL中调用SQLite'repo',返回IList<station>(已填充)

    <station>

  2. 使用AutoMapper从上面的列表中生成一个新的_loadedStations = await _stationManager.GetStationsAsync();(正确填充)

    List<StationViewModel>

  3. 在单独的方法中,上面的视图模型列表将根据LatLng坐标进行过滤。

    <StationViewModel>

  4. fullStationList = AutoMapper.Mapper.Map<IList<Station>, IList<StationViewModel>>(_loadedStations);遵循上面的代码行。

    : 好吧,我已经“解决了”这个问题,但仍然不知道是什么导致了这个问题。

    <IList<Station>, IList<StationViewModel>>的方法相同,还有另一个方法,包含在var stationList = fullStationList.Where(x => mapBounds.Contains(new LatLng(x.Latitude, x.Longitude))).ToList();中。它也有电台标识符;

    foreach

    通过更改任一变量名称,代码将正常运行,之前错误的循环将运行没有任何问题。

      

    请注意,第二个循环不在第一个循环中 - 显然   不会工作,但我不明白为什么这会导致问题。

2 个答案:

答案 0 :(得分:2)

这似乎与Xamarin的工作方式有关,更改var名称解决了问题

 foreach(var stationItem in stationList)
 {

     // Breakpoint on next line shows station to be null..!
     if(stationItem.ClusterId != Guid.Empty)
     {
         // Code in here
     }
 }

答案 1 :(得分:0)

我以这种方式尝试过它并且有效:

internal class CStation
{
    private Guid _clusterId;

    public CStation()
    {

        _clusterId = Guid.NewGuid(); 
    }

    public Guid StationName
    {
        get { return _clusterId; }
    }
}

private voit TestList()
{

    List<CStation> stationList = new List<CStation>();
    CStation test1 = new CStation();
    CStation test2 = new CStation();
    CStation test3 = new CStation();
    stationList.Add(test1);
    stationList.Add(test2);
    stationList.Add(test3);

    foreach (var station in stationList)
    {

        // Breakpoint on next line shows station to be null..!
        if (station == null )
        {
            throw new  ArgumentNullException();
        }
    }
}

我认为你没有实例化Guid。 我是在Station的构造函数中完成的 - &gt; _clusterId = Guid.NewGuid();