2012-08-07 6 views
5

otrzymuję następujący błąd:C# generics error: Ograniczenia dla parametru typu "T" metody ...?

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.

Klasa:

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

Interfejs:

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

Odpowiedz

16

Jesteś ograniczając swój T rodzajowe parametru na klasy w swojej realizacji. Nie masz tego ograniczenia w interfejsie.

Musisz usunąć go z klasy lub dodać go do interfejsu pozwolić kompilacji kodu:

Ponieważ jesteś wywołanie metody CreateObjectSet<T>(), który requires the class constraint, czego potrzeba, aby dodać go do swojego interfejsu.

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

hej Dutchie goed człowiek – user603007

+0

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

+0

hier w OZ wat minder :) thanks anyway – user603007

3

albo trzeba zastosować ograniczenie metody interfejsu jak dobrze lub usunąć go z realizacji.

Zmieniasz umowę interfejsu poprzez zmianę ograniczenia w realizacji - to nie jest dozwolone.

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

Musisz także ograniczyć interfejs.

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