问题
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