2012-08-07 191 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; 
}