无法将通用类转换为通用接口,为什么? [英] Cannot convert Generic Class to Generic Interface, why?

查看:88
本文介绍了无法将通用类转换为通用接口,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从IRepository<TObject>继承的IRepository接口.我也有一个从S QLRepository<TObject>继承的SqlRepository类,该类又实现了IRepository<TObject>.为什么不能将SqlRepository的实例实例化为IRepository?

I have an IRepository interface that inherits from IRepository<TObject>. I also have a SqlRepository class that inherits from SQLRepository<TObject>, which in turn implements IRepository<TObject>. Why can't I instantiate a instance of SqlRepository as an IRepository?

public class MyObject : IObject {
    ...
}

public interface IRepository<TObject> where TObject : IObject, new() {
    ...
}

public interface IRepository : IRepository<MyObject> { }

public class SqlRepository<TObject> : IRepository<TObject> where TObject : IObject, new() {
    ...
}

public class SqlRepository : SqlRepository<MyObject> { }

public class Controller {
    private IRepository _repository;

    public Controller() {
        _repository = new SqlRepository();
    }
}

上面的示例在尝试将新的SqlRepository分配给Controller类中的_repository时失败,并显示以下错误消息.

The example above fails when trying to assign a new SqlRepository to _repository in the Controller class, with the following error message.

Argument '1': cannot convert from 'SqlRepository' to 'IRepository'

我没有掌握继承的基本原理,请帮忙.

Which basic principle of inheritance have I failed to grasp, please help.

推荐答案

因为IRepositoryIRepository<MyObject>,而不是相反.

基本上:

SqlRepositorySqlRepository<MyObject>
这是IRepository<MyObject>.
为此,您应该根据自己的意愿从IRepository继承IRepository<TObject>或使SqlRepository实现IRepository.

SqlRepository is a SqlRepository<MyObject>
which is an IRepository<MyObject>.
To make that work, you should either inherit IRepository<TObject> from IRepository or make SqlRepository implement IRepository depending in your intention.

此问题根本不是泛型特有的.假设:

This issue is not generics-specific at all. Assume:

interface IMovable { }
interface IDrivable : IMovable { } 
class Ball : IMovable { }

很明显,Ball不是IDrivable而是IMovable.

这篇关于无法将通用类转换为通用接口,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆