Named parameters with params

2020-06-08 02:45发布

问题:

I have a method for getting values from database.

 public virtual List<TEntity> GetValues(
           int? parameter1 = null,
           int? parameter2 = null,
           int? parameter3 = null,
           params Expression<Func<TEntity, object>>[] include)
        {
            //...
        } 

How can I call this function with named parameter to not write all parameters before include? I want to do something like this

var userInfo1 = Unit.UserSrvc.GetValues(include: p => p.Membership, p => p.User);

But this doesn't seem working? How can I use named parameter with params?

回答1:

I think the only way is something like:

GetValues(include:
   new Expression<Func<TEntity, object>>[] { p => p.Membership, p => p.User })

Which is not that great. It would be probably best if you added an overload for that:

public List<Entity> GetValues(params Expression<Func<Entity, object>>[] include)
{
    return GetValues(null, null, null, include);
}

Then you call your method just like

GetValues(p => p.Membership, p => p.User)


回答2:

A params argument works like an array, try this syntax:

var userInfo1 = Unit.UserSrvc.GetValues(include: new Expression<Func<TEntity, object>>[] { p => p.Membership, p => p.User });

(Might need some adapting due to the generic parameter, but I think you get the gist of it)