C # Abstract General Method

C # ,. net 3.5

I am trying to create a base class that has a common method. Classes that inherit from it must indicate the type of method.

The premise for this is to create classes that control filtering.

So, I have a:

public abstract class FilterBase { //NEED Help Declaring the Generic method for GetFilter //public abstract IQueryable<T> GetFilter<T>(IQueryable<T> query); } public class ProjectFilter:FilterBase { public IQueryable<Linq.Project> GetFilter(IQueryable<Linq.Project> query) { //do stuff with query return query; } } public class ProjectList { public static ProjectList GetList(ProjectFilter filter) { var query = //....Linq code... query = filterCriteria.GetFilter(query); } } 

Think that this is something simple, but I can’t get the syntax directly in FilterBase for the abstract GetFilter method.

EDIT

Ideally, I would like to save only the method as a general, and not a class. If this is not possible, then please let me know ..

+6
generics c # linq
source share
3 answers

Make the FilterBase class itself generic.

 public abstract class FilterBase<T> { public abstract IQueryable<T> GetFilter(IQueryable<T> query); } 

This will allow you to create the ProjectFilter class as follows:

 public class ProjectFilter : FilterBase<Linq.Project> { public override IQueryable<Linq.Project> GetFilter(IQueryable<Linq.Project> query) { //do stuff with query return query; } } 
+15
source share
  public abstract class FilterBase<T> { public abstract IQueryable<T> GetFilter<T>(IQueryable<T> query); } 
+4
source share

Of course, you can have an abstract general method:

 public abstract class FilterBase { public abstract IQueryable<T> GetFilter<T>(IQueryable<T> query); } 

The problem is that this does not mean what you want. It can be called for any T In particular, the following should work, since ProjectFilter comes from FilterBase :

 FilterBase fb = new ProjectFilter(...); IQueryable<string> query = ...; IQueryable<string> filter = fb.GetFilter<string>(query); 

So FilterBase cannot just implement GetFilter<Linq.Project> . It should implement GetFilter<string> , GetFilter<int> , etc .; in short, GetFilter<T> . Therefore, you can see that this is not a limitation.

+2
source share

All Articles