我希望能够通过调用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();
}
答案 0 :(得分:0)
为您的商品创建一个界面 ,其中包含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();
}
}