Does the params keyword guarantee items to be in the same order as they are listed?
I'm working on a simple API that will accept a number of IBehaviours which are then applied in configuration. I am designing this using the params keyword since often there is just one behaviour wanted, but sometimes more.
However, it is very important that behaviours are applied in the correct order.
public void Configure(string wow, params IBehaviour[] behaviours) { ... }
Configure("oh yes", new MustHappenFirst(), new MustHappenSecondly());
Does this
Technically imply that
behaviours
occurs in the same order when enumerating? (as in standard-wise, not simply practically-wise).Semantically and intu开发者_如何学Goitively convey that same behaviour?
Thanks.
The evaluation of the arguments will happen in left-to-right order and they'll be put into the array in that order.
Note that if "null" is a valid value for a behaviour, you can get into trouble:
Configure("hello", null);
calls
Configure("hello", (IBehaviour[]) null);
not
Configure("hello", new IBehaviour[1] { null } );
so be careful with that.
Yes. When you use params
, the compiler just turns the arguments into an array, in the same order that the arguments were listed in the program. They will always be in this order inside the method.
A call to:
Configure("wow", one, two, three);
Will always map to:
Configure("wow", new[] {one, two, three});
Yes. Parameters specified for a method using the params keyword will be placed in the params array in the order they are specified in the method call. This is generally understood to be so by developers, who are familiar with params-using methods like String.Format where the order of a formatting value in the parameter list is very important.
Yes; order is preserved.
Yes; this is fine.
精彩评论