可选参数

发布于 2024-07-29 03:08:04 字数 179 浏览 4 评论 0原文

我有一个需要一堆可选参数的方法,并且我正在重载该方法以提供不同的签名组合。 智能感知会弹出一堆不同的签名,但我认为它现在看起来很混乱,因为我需要提供不同的组合,而不仅仅是在方法签名末尾构建参数。

我是否应该不重载我的方法并坚持一个签名,以便我的方法的用户必须传递空值? 它会使签名更清晰,但会使调用代码看起来更混乱。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

空心空情空意 2024-08-05 03:08:04

您是否仅限于使用 C# 1-3? C# 4 支持可选参数和命名参数...

在那之前,您可能应该坚持重载创建一个具有可变属性的单独类,例如

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

这都可以完成如果您想要在一条语句中...并且某些属性是必需的,则可以在 FooOptions 中创建一个接受所有属性的构造函数。

在 C# 4 中,您可以这样写:

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

如果构造函数被编写为

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

命名参数和可选参数,那么在 C# 4 中构造具有可选属性的不可变类型会变得更加容易:)

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, e.g.

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 :)

江心雾 2024-08-05 03:08:04

考虑一下 C# 方法的 params 参数。

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

Think about params argument of c# method.

void test(params object []arg) {
   ..
}
他夏了夏天 2024-08-05 03:08:04

如果函数定义仅在长度上有所不同(而不是顺序,否则这不会是最好的方法)。然后在函数中,您可以根据参数输入设置所需的值

You could use the params keyword if the function definitions only vary in length (and not order, otherwise this wont be the best approach).Then in the function you can setup the values you need based on the parameter input

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文