Named Parameters and the params keyword in C# [duplicate]

Deadly 提交于 2021-01-02 05:05:22

问题


I have a C# method with a variable length argument list declared using the params keyword:

public void VariableLengthParameterFunction (object firstParam, 
                                             params object[] secondParam)

Is there any way of using named parameters when calling the method?


回答1:


You can call it using named parameter like this:

VariableLengthParameterFunction(
    secondParam: new object[] { 5, 7, 3, 2 }, 
    firstParam: 4);



回答2:


EDIT: I assumed you want to access the params object[] secondParam array using named parameters.

Currently only the code inside the method knows what secondParam may contain. From just the method signature there's no link between the object[] and names/types for each element within that array.

Furthermore, since you're using the params keyword, there is no way of supplying secondParam[1] without supplying a value for secondParam[0] (or null).

Perhaps you could create an overload which takes named parameters, and which creates the object[] and then calls this method. Or the other way around.



来源:https://stackoverflow.com/questions/16193871/named-parameters-and-the-params-keyword-in-c-sharp

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