c#-4.0 - C# 泛型错误 : The constraints for type parameter 'T' of method . ..?

标签 c#-4.0 generics entity-framework-4

出现以下错误:

Error 1 The constraints for type parameter 'T' of method
'genericstuff.Models.MyClass.GetCount<T>(string)' must match the constraints for type
parameter 'T' of interface method 'genericstuff.IMyClass.GetCount<T>(string)'. Consider
using an explicit interface implementation instead.

类(class):

 public class MyClass : IMyClass
 {
     public int GetCount<T>(string filter)
     where T : class
       {
        NorthwindEntities db = new NorthwindEntities();
        return db.CreateObjectSet<T>().Where(filter).Count();
       }
 }

界面:

public interface IMyClass
{
    int GetCount<T>(string filter);
}

最佳答案

您将 T 泛型参数限制为实现中的类。您的界面没有此限制。

您需要将其从类中删除或将其添加到接口(interface)中才能编译代码:

由于您正在调用方法CreateObjectSet<T>() ,其中 requires the class constraint ,您需要将其添加到您的界面中。

public interface IMyClass
{
    int GetCount<T>(string filter) where T : class;
}

关于c#-4.0 - C# 泛型错误 : The constraints for type parameter 'T' of method . ..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11845964/

相关文章:

c# - DbContext 表映射

wpf - 从合并序列中删除 IObservable

c# - 按 Entity Framework 中的子集合排序

c# - 指定编码 XmlSerializer

c# - 如何使用反射调用通用扩展方法?

optimization - Swift 泛型能否帮助函数根据类以不同方式处理参数?

Java:从具有指定类型的泛型类扩展

c# - 在 Entity Framework 上运行原始 SQL 查询的 KeyValuePair

c# - 必须声明标量变量 "@dom"

c#-4.0 - 将 MultipartFileData 文件保存到磁盘