我写了一类账户对象并持有静态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);
}
}
最佳答案
另一种选择是使用 List.FindIndex ,并传递一个谓词。即:
if ((index = AccountList.FindIndex(a => a.name == account.name)) >= 0)
AccountList[index] = account;
这样您就可以搜索任意字段或任意数量的字段。如果您无法访问 Account
的源代码以添加重载的 Equals
方法,这将特别有用。
关于c# - List<T>.IndexOf() 如何对自定义对象进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003883/