【问题标题】:c# Generic cannot convert source type to target typec# Generic 无法将源类型转换为目标类型
【发布时间】:2013-12-10 12:49:01
【问题描述】:

我在我的项目中使用存储库模式。每个组件都有一个 Bll 类。

我想创建一个基础 bll 类,子 Bll 类可以在没有相同的 Repository Curd 方法的情况下工作。

但似乎“无法将 ..DriverRepository 转换为目标类型 ...Repository IEntity>”

语言:c#

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class , IEntity
{

    protected string ConnectionStringName;
    protected IDatabase Db;

    public Repository(string connStringName)
    {
        ConnectionStringName = connStringName;
        Db = new Database(ConnectionStringName);
    }
    public Repository()
    {
        ConnectionStringName = "DefaultConnection";
        Db = new Database(ConnectionStringName);
    }
}

public abstract class BaseBll
{
    protected Repository<IEntity> DefaultRepository;

    protected BaseBll(Repository<IEntity> repository)
    {
        _defaultRepository = repository;
    }    
    protected virtual List<IEntity> GetAll()
    {
        return DefaultRepository.GetAll();
    }
}

public class DriverRepository : Repository<Driver>
{
    public Driver GetDriverByLicenseNumber(string licenseNumber)
    {
        return Db.SingleOrDefault<Driver>("where LicenseNumber = @0", licenseNumber);
    }
}

public class DriverBll
{
    public DriverBll()
    {
        DefaultRepository = new DriverRepository();
        //***Throw the Cannot convert ... to ... Error. Why?****
    }
}

但是……

【问题讨论】:

  • 什么是MyRepository
  • 在DriverRepo中创建构造函数,传递连接字符串并调用基构造函数传递连接字符串?
  • 我看到“受保护的 MyRepository DefaultRepository;”。你能发布 MyRepository 类代码吗?
  • 对不起 MyRepository 。这只是一个测试。不管我用不用,不能转换是存在的。
  • 虽然你的代码不是这样,但我猜DriverBll必须继承自BaseBll。然后,您必须确保 Driver 类继承自 IEntity。是这样吗?

标签: c# oop generics


【解决方案1】:

Repository 中没有零参数构造函数,但 DriverRepository 继承自它。因为Repository 中没有零参数构造函数,所以当DriverRepository 尝试创建自己时,它没有构造函数可以调用Repository。您需要像这样从DriverRepository 的构造函数调用Repository(connectionString) 构造函数。

public DriverRepository(string connectionString) : base(connectionString)
{
    ...
}

public DriverRepository() : base("YourConnectionString")
{
    ...
} 

编辑:经过澄清。 首先在这个代码示例中,DriverBll 没有从BaseBll 扩展,因此它不知道DefaultRepository 属性。其次,Driver 必须实现 IEntity

【讨论】:

  • 对不起,我忘了复制那个构造函数:
  • code public Repository() { ConnectionStringName = "DefaultConnection"; Db = 新数据库(连接字符串名称); }
  • 在这种情况下,我们需要您的 MyRepository 类来进一步处理。
  • 对不起MyRepository~
  • 关于编辑:这也无济于事,因为 Repository&lt;Driver&gt; 根本不与 Repository&lt;IEntity&gt; 赋值兼容,除非使用通用协/逆变,即使 Driver 实现 @ 987654339@.
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多