简体   繁体   English

可选参数

[英]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. Intellisense弹出一堆不同的签名,但是我认为现在看起来很混乱,因为我需要提供不同的组合,而不仅仅是在方法签名的末尾建立参数。

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#1-3? C# 4 supports optional parameters and named arguments... C#4支持可选参数和命名参数...

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. 如果需要,可以在一条语句中完成所有操作,如果某些属性是强制性的,则在FooOptions创建一个FooOptions所有属性的构造函数。

In C# 4 you'd be able to write: 在C#4中,您可以编写:

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 :) 命名参数和可选参数应该使在C#4中使用可选属性构造不可变类型变得容易得多:)

Think about params argument of c# method. 考虑一下c#方法的params参数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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