我很难找到索引器来处理对象列表。我希望能够通过名称(字符串)而不是索引来访问列表中的每个对象。因此,我想让[]操作符过载以实现这一点。到目前为止,我无法让超载出现在intellisense中,而且它目前无法工作。到目前为止,我得到的是:
名为MapInfo的类的单例对象:
MapInfo mi = MapInfo.Instance;在MapInfo类中,我有一个表对象列表:
List<Table> tables;
public List<Table> Tables
{
get { return tables; }
}最后,在Tables类中,我尝试了这样的方法:
class Table : IEnumerable<Table>
{
public Table this[string tableName]
{
get
{
foreach (Table table in this)
{
if (table.name == tableName)
return table;
}
return null;
}
}我希望能够使用以下方法访问我的Table对象:
mi.Tables["SomeTableName"]这是我第一次尝试这个,所以我不太确定我哪里出了问题。
发布于 2014-06-19 11:11:09
您可以使用这样的方法
public class MapInfo {
private readonly TableCollection _tables = new TableCollection();
public TableCollection Tables {
get { return _tables; }
}
}
public class TableCollection : List<Table> {
public Table this[string name] {
get { return this.FirstOrDefault(t => t.Name == name); /*using System.Linq;*/ }
}
}
public class Table {
public string Name { get; set; }
}或者像丹纳多建议的那样,简单地使用字典(Dictionary<string, Table>)。但不是像他编码的那样两者兼而有之
IMO,正确的方法是不要使用这样的索引器,因为正如我所看到的,集合中可能有多个具有“唯一”名称的表。我建议使用一个简单的表列表和一个像GetTableWithName这样的方法来使事情更清楚,因为索引器通常会给出一个(false)希望您的数据是唯一的
或者,您可以用FirstOrDefault替换对SingleOrDefault的调用,这将在内部确保如果有一个元素具有“名称”,则没有其他元素具有相同的“名称”
发布于 2014-06-19 10:56:49
您正在重载表类上的索引器。您的代码结构有问题。该表类是一个IEnumerable<Table>,因此一个表包含其他表。
因此,List<Table>将包含表实例,而表实例也包含表实例。
使用mi.Tables["SomeTableName"],您正在尝试访问列表的索引器,而不是表的索引器。
为什么不在MapInfo中定义索引器呢?
发布于 2014-06-19 11:00:52
使用字典
Private Dictionary<String, Table> tables;
public Dictionary<String, Table> Tables
{
get { return tables; }
}然后:
class Table : IEnumerable<Table>
{
public Table this[string tableName]
{
get
{
Table table;
if(mi.tables.TryGetValue(tableName, out table))
{
return table;
}
else
{
return null;
}
}
}
}https://stackoverflow.com/questions/24304643
复制相似问题