【发布时间】:2015-12-14 08:18:55
【问题描述】:
我有这个方法:
public T GetRepositoryByType<T>() where T : IContextDependent
{
var instance = this.Repositories.SingleOrDefault(x => x is T);
return (T)instance;
}
这需要能够返回任何实现IContextDependent 的存储库实例,因此我可以手动为每个存储库设置 DbContext。
当我构建时出现此错误:
错误 CS0425 方法的类型参数“T”的约束 “RepositoryProvider.GetRepositoryByType()”必须与 接口方法的类型参数“T”的约束 'IRepositoryProvider.GetRepositoryByType()'。考虑使用一个 而是显式的接口实现。
但是,如果我考虑来自MSDN 的这段代码:
void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
T temp;
if (lhs.CompareTo(rhs) > 0)
{
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
我看不出有什么直接的区别(除非需要进一步的泛型依赖?)。
仅供参考,界面非常简单:
public interface IContextDependent
{
void SetContext(MyEntities context);
}
还有 IRepositoryProvider 接口:
public interface IRepositoryProvider
{
T GetRepositoryByType<T>();
}
导致错误的原因是什么?
【问题讨论】:
-
我已经添加了接口。我的
IRepositoryProvider是否应该从IContextDependent继承?
标签: c# .net entity-framework generics dependency-injection