【问题标题】:There is no implicit reference conversion to system IDispose没有对系统 IDispose 的隐式引用转换
【发布时间】:2013-11-27 16:12:08
【问题描述】:

我有一个 UnitOfWork 类,我需要将其编码为 Generic,但是当我在控制器中实例化此类时,我收到构建错误“ProjectName.Models.Person 不能用作类型参数 TEntity。没有隐式引用转换从 ProjectName.Models.Person 到 System.IDisposable”。

这是我的工作单元类,它实现了 IDisposiable 并需要一个 TEntity 类类型。这个类没有构建错误:

public class UnitOfWork<TEntity> where TEntity : class, IDisposable
{
    private RogDataContext context = new RogDataContext();
    private GenericRepository<TEntity> thisRepository;

     public GenericRepository<TEntity> DataRepository
    {
        get {
            if (this.DataRepository == null)
            {
                this.thisRepository = new GenericRepository<TEntity>(context);
                return thisRepository;
            }
            return thisRepository;
        }
    }

     public void Save()
     {
         context.SaveChanges();
     }

     private bool disposed = false;

     protected virtual void Dispose(bool disposing)
     {
         if (!this.disposed)
         {
             if (disposing)
             {
                 context.Dispose();
             }
         }
         this.disposed = true;
     }

     public void Dispose()
     {
         Dispose(true);
         GC.SuppressFinalize(this);
     }
    }
}

这是我的 MVC 控件,它在为 Person 类声明私有 unitOfWork 对象时抛出错误:

public class PersonController : Controller
{

    private UnitOfWork<Person> unitOfWork;//<<<< ERROR

    public PersonController()
    {
        this.unitOfWork = new UnitOfWork<Person>();
    }

  //methods ....

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    当前的 UoW 定义要求 TEntity(即 Person)是一次性的(您已将 IDisposable 置于泛型类型的约束中)

    public class UnitOfWork<TEntity> where TEntity : class, IDisposable
    

    但我认为您希望 UoW 是一次性的,并且实体是参考类型。因此,将定义更改为

    public class UnitOfWork<TEntity> : IDisposable
        where TEntity : class
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2017-11-25
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多