这里没有黑魔法:ICollection
没有顺序,仅提供Add
/ Remove
方法。您唯一的解决方案是检查实际的实现是否还包括其他内容,例如IList
:
public static void Swap(this ICollection collection, T oldValue, T newValue) { // In case the collection is ordered, we'll be able to preserve the order var collectionAsList = collection as IList ; if (collectionAsList != null) { var oldIndex = collectionAsList.IndexOf(oldValue); collectionAsList.RemoveAt(oldIndex); collectionAsList.Insert(oldIndex, newValue); } else { // No luck, so just remove then add collection.Remove(oldValue); collection.Add(newValue); } }