简体   繁体   中英

Optional parameters

I've got a method that takes a bunch of optional parameters and I'm overloading the method to supply the different combinations of signatures. Intellisense pops up with a bunch of different signatures but I think it looks quite confusing now because there are different combinations I need to provide, not just building up parameters on the end of the method signature.

Should I just not overload my method and stick to one signature so that the user of my method has to pass in nulls? It would make the signature clearer but makes the calling code look messier.

Are you restricted to using C# 1-3? C# 4 supports optional parameters and named arguments...

Until then, you should probably either stick with overloading or create a separate class with mutable properties, eg

FooOptions options = new FooOptions { Name="Jon", Location="Reading" };
Foo foo = new Foo(options);

That can all be done in one statement if you want... and if some of the properties are mandatory, then create a single constructor in FooOptions which takes all of them.

In C# 4 you'd be able to write:

Foo foo = new Foo(name: "Jon", location: "Reading");

if the constructor was written as

public Foo(string name,
           int age = 0,
           string location = null,
           string profession = null)

Named arguments and optional parameters should make it a lot easier to construct immutable types with optional properties in C# 4 :)

Think about params argument of c# method.

void test(params object []arg) {
   ..
}

如果函数定义仅在长度上有所变化(而不是顺序),则可以使用params关键字 。然后在函数中,您可以根据参数输入来设置所需的值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM