无法使泛型正常工作-不接受变量

时间:2018-11-30 23:13:34

标签: c# generics

我正在尝试基于通用方法中的输入变量返回一个对象,但得到

  

类型T不能用作通用类型的类型参数T   或方法IApiDbRepository<T>没有隐式引用   从TIApiBase

的转换

代码

public interface IApiDbUnitOfWork
{
    IApiDbRepository<T> GetRepo<T>() where T : class, IApiBase;
    Task<int> SaveChangesAsync();
    IApiDbContextHelper Helper { get; }
}

public class ApiDbUnitOfWork : IApiDbUnitOfWork
{
    private readonly IApiDbContextHelper _helper;
    private IApiDbContextHelper dbHelper;

    public ApiDbUnitOfWork(IApiDbContextHelper helper)
    {
        _helper = helper;
    }

    /// <summary>
    /// Returns specified repo
    /// </summary>
    /// <typeparam name="T">Type of repo</typeparam>
    /// <returns>A repo based on specified type</returns>
    public IApiDbRepository<T> GetRepo<T>() where T : class, IApiBase
    {
        return new ApiDbRepository<T>(_helper);
    }

    /// <summary>
    /// Async save changes to database
    /// </summary>
    /// <returns>Number of entries written to the database</returns>
    public async Task<int> SaveChangesAsync()
    {
        return await _helper.DataContext.SaveChangesAsync();
    }

    public IApiDbContextHelper Helper => _helper;
}

ApiBase

public interface IApiBase
{
    int Id { get; set; }
    Guid UId { get; set; }
    DateTime DateCreated { get; set; }
    bool Active { get; set; }
}

public abstract class ApiBase : IApiBase
{
    public int Id { get; set; }
    public Guid UId { get; set; } = Guid.NewGuid();
    public DateTime DateCreated { get; set; } = DateTime.Now;
    public bool Active { get; set; } = true;
}

解决方案中的每个对象都继承自IApiBase

0 个答案:

没有答案