Named parameters with params

扶醉桌前 提交于 2019-12-21 03:15:07

问题


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)



来源:https://stackoverflow.com/questions/9871927/named-parameters-with-params

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!