c#泛型错误:方法的类型参数'T'的约束......?

use*_*007 10 generics entity-framework-4 c#-4.0

收到以下错误:

错误1类型参数' T'of method
' genericstuff.Models.MyClass.GetCount<T>(string)'的约束必须与接口方法' '的类型
参数' T' 的约束匹配genericstuff.IMyClass.GetCount<T>(string).请考虑
使用显式接口实现.

类:

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

接口:

public interface IMyClass
{
    int GetCount<T>(string filter);
}
Run Code Online (Sandbox Code Playgroud)

Wou*_*ort 26

您正在将T通用参数限制为实现中的类.您的界面没有此约束.

您需要从类中删除它或将其添加到您的接口以让代码编译:

由于您正在调用需要类约束的方法CreateObjectSet<T>(),因此需要将其添加到接口.

public interface IMyClass
{
    int GetCount<T>(string filter) where T : class;
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*rth 5

您还需要将约束应用于接口方法,或者将其从实现中删除。

您正在通过更改实现的约束来更改接口契约 - 这是不允许的。

public interface IMyClass
{
    int GetCount<T>(string filter) where T : class;
}
Run Code Online (Sandbox Code Playgroud)