2010-11-09 51 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