通用方法约束错误 - 请考虑使用显式接口实现

时间:2015-12-14 08:18:56

标签: c# .net entity-framework generics dependency-injection

我有这个方法:

public T GetRepositoryByType<T>() where T : IContextDependent
{
    var instance = this.Repositories.SingleOrDefault(x => x is T);

    return (T)instance;
}

哪个需要能够返回任何实现IContextDependent的存储库实例,因此我可以手动为每个实例设置DbContext。

当我构建时,我收到此错误:

  

错误CS0425类型参数的约束&#39; T&#39;方法   &#39; RepositoryProvider.GetRepositoryByType()&#39;必须匹配   类型参数的约束&#39; T&#39;接口方法   &#39; IRepositoryProvider.GetRepositoryByType()&#39 ;.考虑使用   显式接口实现。

但是,如果我从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>();
}

导致错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

  

<强> RepositoryProvider .GetRepositoryByType()&#39;必须匹配类型参数的约束&#39; T&#39;接口方法&#39; IRepositoryProvider .GetRepositoryByType()&#39;

您对 RepositoryProvider 的约束是:where T : IContextDependent
因此,对 IRepositoryProvider 的约束必须where T : IContextDependent

也就是说,您的界面应该写成如下:

public interface IRepositoryProvider
{
    T GetRepositoryByType<T>() where T : IContextDependent;
}