C# 4.0 命名参数 - 在调用非框架方法时是否应该始终使用它们?

发布于 2024-08-31 21:24:10 字数 176 浏览 3 评论 0原文

我确实这是一个非常主观的主题,但这是我目前的看法:

当调用不构成 .NET BCL 命名参数一部分的方法时,应始终使用方法签名,因为方法签名可能会发生变化,尤其是在我自己的开发周期中应用程序。

尽管它们可能看起来更冗长,但它们也更清晰。

以上是调用方法的合理方法还是我忽略了一些基本的东西?

I really this is a hugely subjective topic but here is my current take:

When calling methods which do not form part of the .NET BCL named parameters should always be used as the method signatures may well change, especially during the development cycle of my own applications.

Although they might appear more verbose they are also far clearer.

Is the above a reasonable approach to calling methods or have I overlooked something fundamental?

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

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

发布评论

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

评论(1

牵你的手,一向走下去 2024-09-07 21:24:10

就我个人而言,我认为这是过分的。 (我还认为,将它们称为命名参数更正确、更清晰 - 参数总是有名称,因为这是声明的一部分。)

在许多情况下,含义是明确的从方法名称中可以清楚地看出 - 特别是如果只有几个参数。为什么要费力添加名字呢?为什么名称可能会改变这一事实会影响这一点?

我建议使用命名参数:

  • 当还使用可选参数时
  • 当有多个相同类型的参数时,因此它们可能会被混淆(例如对话框的标题和内容文本)
  • 当您使用 null 对于参数,并不清楚它在做什么

换句话说,在 C# 4 之前,没有命名参数是否经常导致您感到困惑?就我而言,这肯定是非零次数 - 上面的情况确实发生过 - 但这并不是经常妨碍我的事情。可选参数使方法(或特别是构造函数)具有潜在的多个参数更加合理,这导致命名参数更有用(如果您想指定跳过早期参数的“后期”可选参数,则确实有必要)。

I think it's over the top, personally. (I also believe it's more correct and clearer to call them named arguments - the parameters always have names, as that's part of the declaration.)

In many cases the meaning is crystal clear from the method name - particularly if there are only a couple of arguments. Why bother to add the name? Why does the fact that the name may change affect this?

I would suggest using named arguments:

  • When optional parameters are also being used
  • When there are multiple parameters of the same type, so they can be confused (e.g. a dialog box's title and content text)
  • When you're using null for an argument, and it's not clear what it's doing

To put it another way, how often did not having named arguments cause you confusion before C# 4? In my case it's certainly a non-zero number of times - the situations above do happen - but it's not something that regularly got in my way. Optional parameters make it more reasonable for a method (or particularly a constructor) to have potentially many parameters, and that leads to named arguments being more useful (and indeed necessary if you want to specify "late" optional parameters having skipped earlier ones).

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