2012-08-07 174 views
5

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

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.

类:

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); 
} 

回答

16

你限制你的T泛型参数类中您的实现。你的界面没有这个限制。

您需要从类中删除,或将其添加到您的界面,让代码编译:

既然你调用的方法CreateObjectSet<T>(),其中requires the class constraint,你需要将它添加到你的界面。

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

hey Dutchie goed man – user603007 2012-08-07 12:39:52

+0

Er lopen hier best wat Nederlanders rond inderdaad! :) – 2012-08-07 12:40:57

+0

在OZ笏意见塔:)但无论如何 – user603007 2012-08-07 12:59:36

3

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

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

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

您也需要限制您的接口。

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