简体   繁体   中英

C# Abstract Generic Method

C#, .net 3.5

I am trying to create a base class that has a generic method. Classes that inherit from it should specify the method's type(s).

The premise for this is for creating classes that manage filtering.

So I have:

 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 it is something simple, but I can't get the syntax right in FilterBase for the GetFilter abstract method.

EDIT

Ideally, would like to keep only the method as generic and not the class. If not possible, then please let me know..

Make the FilterBase class itself generic.

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

This would enable you to create your ProjectFilter class like this:

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

Of course, you can have an abstract generic method:

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

The problem is that it doesn't mean what you want. It can be called for any T . In particular, the following must work, since ProjectFilter derives from FilterBase :

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

So FilterBase can't just implement GetFilter<Linq.Project> . It needs to implement GetFilter<string> , GetFilter<int> , etc.; in short, GetFilter<T> . So you can see it isn't a limitation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM