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();
}
Run Code Online (Sandbox Code Playgroud)
我在这篇文章中得到了一些帮助:尝试调用 int IList<Location>.IndexOf(Location item) 方法
我试图让它工作,但我似乎总是得到 -1 作为索引号。我知道字符串site = loc.Site;是空的,所以我现在不知道如何从 IList 中获取索引。
为了弄清楚我想要完成的任务,我想学习如何使用 IList 接口成员,并且我从 IndexOf 接口开始。
IList 中填充的不仅仅是“sSite”,但出于示例目的,我只是将列表缩减为“sSite”。
因此,在学习过程中,我遇到了这个障碍,并盯着代码看了几天(是的,我休息了一下,看看其他东西,以免让自己疲惫不堪)。
所以主要问题是我不断得到index = -1。
小智 5
我不清楚你在这里的意图是什么,但在代码片段中从未使用过“loc”,因为你Location在“Add”方法中创建了一个新的,而“site”(正如你所指出的)始终为空,但在“Add”方法传递一个值并将其设置在新创建的实例上,因此除非您传递 string.Empty 作为值,否则比较i.Site == site将始终为false。如果删除这些并重写为:
Locations test = new Locations();
string sSite = "test";
test.Add(sSite);
Location finding = test.Where(i => i.Site == sSite).FirstOrDefault();
int index = test.IndexOf(finding);
Run Code Online (Sandbox Code Playgroud)
0然后它作为索引返回。