【发布时间】:2012-03-22 19:49:23
【问题描述】:
class IList2
{
static void Main(string[] args)
{
Locations test = new Locations();
Location loc = new Location();
string sSite = "test";
test.Add(sSite);
string site = loc.Site;
Location finding = test.Where(i => i.Site == site).FirstOrDefault();
int index = finding == null ? -1 : test.IndexOf(finding);
}
}
public class Location
{
public Location()
{
}
private string _site = string.Empty;
public string Site
{
get { return _site; }
set { _site = value; }
}
}
public class Locations : IList<Location>
{
List<Location> _locs = new List<Location>();
public Locations() { }
public int IndexOf(Location item)
{
return _locs.IndexOf(item);
}
//then the rest of the interface members implemented here in IList
public void Add(string sSite)
{
Location loc = new Location();
loc.Site = sSite;
_locs.Add(loc);
}
}
IEnumerator<Location> IEnumerable<Location>.GetEnumerator()
{
return _locs.GetEnumerator();
}
我在这篇文章中得到了一些帮助:Trying to call int IList<Location>.IndexOf(Location item) method
我试图让这个工作,但我似乎总是得到 -1 作为索引号。我知道字符串 site = loc.Site; 在意识到这一点后是空的,所以我现在不知道如何从 IList 中获取索引。
为了弄清楚我想要完成的工作,我想学习如何使用 IList 接口成员,我从 IndexOf 接口开始。
IList 不仅包含“sSite”,但出于示例目的,我只是将列表简化为“sSite”。
所以在学习的过程中,我遇到了这个障碍,并且盯着代码看了几天(是的,我会休息一下,看看其他的东西,以免让自己筋疲力尽)。
所以主要问题是我不断得到 index = -1。
【问题讨论】:
-
那么你期望哪个索引给出空列表?!
-
这真的让你想做什么感到困惑。在 Main 函数的第 3 行,loc 是什么?我没有看到它在该方法的任何地方声明。
-
感谢尼克指出这一点,我补充了。