【发布时间】:2013-08-02 22:56:51
【问题描述】:
我编写了一个帐户对象类并持有这些帐户对象的静态List<T>。我的程序循环遍历列表中的每个帐户,对帐户执行一些工作,然后在到达列表末尾时在顶部重置。
我的问题是,在我的程序完成使用该帐户后,我需要能够将帐户重新插入到列表中,并添加了一些更新的信息。我可以按照下面的说明执行此操作,使用 IndexOf() 函数检查静态列表中的对象还是会因为我向其中添加数据而失败?我不明白它比较哪些字段以查看两个对象是否相同。
注意:列表中不允许重复,因此不存在更新错误项目的风险
public class Account
{
public string name;
public string password;
public string newInfo;
}
public static class Resources
{
private static List<Account> AccountList = new List<Account>();
private static int currentAccountIndex = 0;
public static Account GetNextAccount()
{
if (currentAccountIndex > AccountList.Count)
currentAccountIndex = 0;
return AccountList[currentAccountIndex++];
}
public static void UpdateAccount(Account account)
{
int index;
if ((index = AccountList.IndexOf(account)) >= 0)
AccountList[index] = account;
}
}
public class Program
{
public void PerformWork()
{
Account account = Resources.GetNextAccount();
// Do some work
account.newInfo = "foo";
Resources.UpdateAccount(account);
}
}
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
你检查documentation了吗?它说“此方法使用默认相等比较器 EqualityComparer
确定相等。默认为 T,即列表中值的类型。” -
如果您在实施自定义
IEqualityComparer或拥有帐户支持IEquateable后不关心订单,则最好使用HashSet降神会,您没有任何重复.
标签: c# .net generics collections