简体   繁体   中英

In C#, how can I pass typed array into generic function?

I have a collection:

 IQueryable<Car>

and i want to pass into a generic function that takes in as a parameter:

 IQueryable<T>

something like (which is sitting in a base class)

   public abstract class  BaseController<T> : ControllerBase  where T : BaseObj, new()
  {

      public IQueryable<T> FilterEntities(IQueryable<T> entities)
     {
     }
  }

what is the right way to pass this in? Cast?, safety cast?

public IQueryable<TQueryable> FilterEntities<TQueryable>(
    IQueryable<TQueryable> entities)
{
}

You need to make the method a generic method (the <T> after the function name before the parens tells the compiler the method is generic).

The type parameter TQueryable of the method differs from the class type. If you don't want it to your method signature should be fine.

your problem is that your method isn't generic, the class is. Notice there' no <T> after then method name, than mean you have to pass in an IQueryable of what ever was yoused for the type argument for the class.

Eg if the object was instantiated like this:

new BaseController<BaseObject>(..) //ignoring that BaseController is abstract

you'd need to pass an IQueryable<BaseObject> so in your case where you wish to pass in an IQueryable<Car> the type of controller needs to derive from BaseController<Car>

If on the other hand you wish the method to be generic change the signature of the method to

public IQueryable<TElement> FilterEntities<TElement>
            (IQueryable<TElement> entities)

that does not include the type contraint on T you have on the type parameter for the class. If this is should be enforced for the generic method the signature needs to be:

public IQueryable<TElement> FilterEntities<TElement>(IQueryable<TElement> entities) 
            where TElement : BaseObj, new()

EDIT If you wish to have a "default" method that simply uses T as the type argument you will have to implement it as a non generic method just as you have in your code so the class would be:

  public abstract class  BaseController<T> : ControllerBase  
                where T : BaseObj, new()
  {

     public IQueryable<T> FilterEntities(IQueryable<T> entities)
     {
            return FilterEntities<T>(entities);
     }

     public IQueryable<TElement> FilterEntities<TElement>(IQueryable<TElement> entities) 
                where TElement : BaseObj, new()
  }

Define the FilterEntities as below

public IQueryable<T> FilterEntities<T>(IQueryable<T> entities)
{
}

Now you can pass IQueryable as below

    IQueryable<Car> x = null; //Initialize it
    FilterEntities<Car>(x);

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