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 接口(interface)成员,我从 IndexOf 接口(interface)开始。
IList 中填充的不仅仅是“sSite”,但出于示例目的,我只是将列表缩减为“sSite”。
所以在学习的过程中,我遇到了这个障碍,并盯着代码看了几天(是的,我休息一下,看看其他东西,以免让自己疲惫不堪)。
所以主要问题是我一直得到 index = -1。
最佳答案
我不清楚您的意图是什么,但在代码片段中从未使用过“loc”,因为您在“Add”方法中创建了一个新的 Location
,而“site”是 (正如您所指出的)始终为空,但在“添加”方法中,您传入一个值并将其设置在新创建的实例上,因此除非您将 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);
然后返回 0
作为索引。
关于c# - 试图在 IList 中获取索引位置的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9829442/