开发者

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

  1. Technically imply that behaviours occurs in the same order when enumerating? (as in standard-wise, not simply practically-wise).

  2. 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.


  1. Yes; order is preserved.

  2. Yes; this is fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜