在派生自 List(T) Class (System.Collections.Generic) 的 class 中实现 Update() 方法

Implement Update() method in a class derived from List(T) Class (System.Collections.Generic)

我希望能够通过调用我的 PersistentList 实例中的方法来更新列表。

public class PersistentList<T> : List<T> where T : class, new()
{
    public void Update(T Item){//...}
}

所以代替:

public ActionResult Edit(Article a)
{
    if (ModelState.IsValid) 
    {                
        Article old = la.Find(p => p.Id == a.Id);
        int index = pl.IndexOf(old);
        pl[index] = a;             
        pl.SaveChanges();
        return this.RedirectToAction("Index", "Home");
    }
    else { return View(); }
}

我想要

public ActionResult Edit(Article a)
{
    if (ModelState.IsValid)
    {                
        pl.Update(a);  //I'll call SaveChanges() in it.
        return this.RedirectToAction("Index", "Home");
    }
    else { return View(); }
}

我有点迷路了。任何提示都会很好!谢谢

这是我到目前为止尝试过的方法:

public void Update(T item)
{
    T old = base.Find(p => p.GetHashCode() == item.GetHashCode());
    int index = base.IndexOf(old);
    base[index] = item;            
    SaveChanges();
}

为您的项目创建一个接口以从 派生包含 Id 属性:

public interface IItem
{
    int Id { get; set; }
}

并为您的列表添加另一个通用约束:

public class PersistentList<T> : List<T> where T : class, new(), IItem
{
    public void Update(T item)
    {
        // T must derive from the interface by constraint
        T old = base.Find(p => p.Id == item.Id);
        int index = base.IndexOf(old);
        base[index] = item;
        SaveChanges();
    }
}