在从List(T)类派生的类中实现Update()方法(System.Collections.Generic)

时间:2022-11-30 14:28:48

I would like to be able to update a list by calling a method in my PersistentList instance.

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

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

so Instead of :

所以不要:

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(); }
}

I want something like

我想要类似的东西

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(); }
}

I'm a little lost. Any tips would be nice! Thank you

我有点失落。任何提示都会很好!谢谢

This is what I tried so far :

这是我到目前为止所尝试的:

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

1 个解决方案

#1


0  

Create an interface for your items to derive from containing the Id property:

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

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

And have another generic constraint for your list on it:

并为您的列表设置另一个通用约束:

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();
    }
}

#1


0  

Create an interface for your items to derive from containing the Id property:

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

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

And have another generic constraint for your list on it:

并为您的列表设置另一个通用约束:

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();
    }
}