问题是您使用的是匿名类型。Items
列表框集合返回的项目以object
. 为了访问项目的属性,您需要强制转换它们,因为类型是匿名的,所以您不能这样做。为您的项目创建一个明确的类。
class UserStatus
{
public string Username { get; set; }
public string Status { get; set; }
public override bool Equals(object obj)
{
UserStatus other = obj as UserStatus;
return other != null && other.Username == Username && other.Status == Status;
}
public override int GetHashCode()
{
unchecked {
int hash = 17;
hash = hash * 31 + Username == null ? 0 : Username.GetHashCode();
hash = hash * 31 + Status == null ? 0 : Status.GetHashCode();
return hash;
}
}
}
现在您可以搜索项目的索引
for (int i = 0; i < playersOnlineList.Items.Count; i++) {
var userStatus = (UserStatus)playersOnlineList.Items[i];
if (userStatus.Username == x) {
userStatus.Status = newStatus;
break;
}
}