请考虑这个接口:C#泛型是关键字协方差/逆变式inferral
public interface IInitialiazableEntity<TRepository> where TRepository : class, IRepository
{
void Initialize(TRepository repository);
}
这个类(片段):
public class SomeFacade<TRepository> where TRepository : class, IRepository
{
public void Add<TEntity>(TEntity entity) where TEntity : AbstractEntity
{
try
{
if (entity is IInitialiazableEntity<TRepository>)
(entity as IInitialiazableEntity<TRepository>).Initialize(this.Repository);
}
catch (Exception ex)
{
this.Logger.Error(ex);
}
}
}
与实体:
public class Student : AbstractEntity, IInitialiazableEntity<IRepository>
{
void Initialize(IRepository repository) { ... }
}
由于学生只有IInitialiazableEntity<IRepository>
和门面将有一个比t更专业的实际储存库他基本上是IRepository
(即它将是IMySpecialRepository : IRepository
),is
关键字会意识到它可以将IMySpecialRepository
强制转换为实体的Initialize
方法?或者如果不是,该怎么做?
你试过了吗?此外,什么是IMySpecialRepository和IMySpecializedRepository? – ken2k 2014-11-03 13:42:02
对不起,我知道我可以测试这个,然后尝试找到一个解决方案,但我很匆忙。我认为这对其他人很有用(因为标题/标签是正确的)。 – 2014-11-03 13:45:28
@ ken2k特殊(ized)存储库(有一个错字,两者是相同的,我纠正了它) - 是从基本IRepository继承的任何东西。 – 2014-11-03 13:47:22