2012-08-07 5 views
5

ottenere il seguente errore:C# errore generics: i vincoli per il parametro tipo "T" del metodo ...?

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.

Classe:

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

Interfaccia:

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

risposta

16

Si sono limitando il parametro generico T in classe nell'implementazione. Non hai questo vincolo sulla tua interfaccia.

è necessario rimuovere dalla tua classe o aggiungerlo alla vostra interfaccia di lasciare che il codice di compilazione:

Dal momento che si sta chiamando il metodo CreateObjectSet<T>(), che requires the class constraint, è necessario aggiungerlo alla vostra interfaccia.

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

hey Dutchie goed uomo – user603007

+0

Er lopen hier migliore wat Nederlanders rond inderdaad! :) –

+0

hier in OZ wat minder :) grazie comunque – user603007

3

È necessario applicare il vincolo anche al metodo dell'interfaccia o rimuoverlo dall'implementazione.

Si sta modificando il contratto di interfaccia modificando il vincolo sull'implementazione - questo non è consentito.

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

È necessario anche limitare l'interfaccia.

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