我有一個應用程序被構造爲一個服務層,它使用存儲庫層進行持久化。 我想創建一個泛型控制器類來重用共享行爲,但我在嘗試設置泛型參數時遇到了問題。以下代碼:隱式轉換en C#泛型類
public class BusinessEntity
{ }
public class Person : BusinessEntity
{ }
public interface IRepository<T> where T : BusinessEntity
{ }
public interface IService<T, R>
where T : BusinessEntity
where R : IRepository<T>
{ }
public partial interface IPersonRepository : IRepository<Person>
{ }
public interface IPersonService : IService<Person, IPersonRepository>
{ }
public abstract class BaseController<X, Y>
where X : BusinessEntity
where Y : IService<X, IRepository<X>>
{ }
public class PersonController : BaseController<Person, IPersonService>
{ }
在編譯失敗並
類型ConsoleApplication.IPersonService
不能在通用類型或方法ConsoleApplication.BaseController<X,Y>
被用作類型參數Y
。有一個從ConsoleApplication.IPersonService
到ConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository<ConsoleApplication.Person>>
這個作品
public interface IPersonService : IService<Person, IRepository<Person>>
沒有隱式引用轉換,但我失去了自定義庫
有一種方法,使編譯器實現IPersonRepository
是IRepository<Person>
?
權,這是因爲'IRepository其中X:Person'是不一樣的'IRepository '默認情況下,默認情況下這種通用類型沒有差異。你正在使用哪個版本的.NET Framework? –
sll
2012-03-07 19:51:54
如果我有能力,我會給你一個「打破編譯器」徽章。從我花了5分鐘的時間努力使其工作,我的直覺結論是,編譯器不夠聰明,無法做你想做的事情。 – PlayDeezGames 2012-03-07 20:03:21
我正在使用.Net 4.我沒有想過差異,我認爲它值得一試。 – 2012-03-08 21:55:23