2010-11-09 57 views
4
interface IModel {} 

class MyModel : IModel {} 

interface IRepo<T> 
    where T: IModel { } 

class Repo : IRepo<MyModel> { } 

//EDIT: A smaller example 
IRepo<IModel> repo = new Repo(); // Cannot implicitly convert.. An explicit convertion exists. Missing cast? 

// Old example: 
/* 
The type 'Repo' cannot be used as type parameter 'C' in the generic type or method. 
'Castle.MicroKernel.Registration.ComponentRegistration<S>.ImplementedBy<C>()'. 
==> There is no implicit reference conversion from 'Repo' to 'IRepo<IModel>'. 
*/ 
container.Register(
    Component.For<IRepo<IModel>>() 
    .ImplementedBy<Repo>()); 

但是,回购是从IRepo派生的,而MyModel是从IModel派生的。为什么这不起作用?派生类型不能隐式转换为基本接口

我尝试添加上回购隐式操作,但它不允许在接口之间转换..

难道这解决了联合/禁忌varience东西从C#4(不,我没有线索我在说什么:))?

回答

2

你的直觉是正确的。这是一个协变问题。你看,IRepo<IModel>IRepo<MyModel>是不一样的。

为了允许协变类型,你可以用out修改修复它在C#4:

interface IRepo<out T> where T: IModel {} 

如果你不是在C#4的是,你将需要收紧您的使用情况:

IRepo<MyModel> repo = new Repo(); 
+0

谢谢。猜猜该考虑升级到C#4了。 – simendsjo 2010-11-09 11:51:52