params Parameter with default parameter values [duplicate]

前提是你 提交于 2021-02-07 12:18:27

问题


I've seen the params parameter more times than I can say and always removed it without thinking about it's meaning. Now I've learned its purpose. What I just learned is that the params parameter must be the last in the parameter list. But this is what I learned about the parameters that have a default value specified. Example:

MyMethod(string Name, int blah=0). 

So the question is if I need to specify a default value as above while needing to use params, can this be done? If so, which must be declared last? Example:

MyMethod(int blah=0, params string[] variableData). 

Thanks for your help again. James


回答1:


Your example is correct:

public void TestMethod(string name = "asdasd", params int[] items)
{
}

params has to be last, no matter what parameter are used before that.




回答2:


Yes, params are a special case here - they're the only situation in which a parameter without a default value can come after one with a default value.

However, you can't then call the method and take advantage of the params side of things (for a non-empty array) without also specifying the optional parameter:

MyMethod(5, "x", "y");                            // Fine, no defaulting
MyMethod(variableData: new string[] { "x", "y"}); // Default for blah
MyMethod();                                       // Default for blah, empty variableData
MyMethod(new string[] { "x, "y" });               // Invalid   
MyMethod("x", "y");                               // Invalid


来源:https://stackoverflow.com/questions/15129296/params-parameter-with-default-parameter-values

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