为什么 C# 4.0 中的可选参数需要编译时常量?

发布于 2024-10-22 07:26:14 字数 30 浏览 8 评论 0原文

还有一种方法可以使用可选方法参数的运行时值吗?

Also is there a way to use run-time values for optional method parameters?

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

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

发布评论

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

评论(3

紙鸢 2024-10-29 07:26:14

可选参数必须是常量,因为它们是作为属性值写出的。因此,它们继承了属性值所具有的所有限制。

无法直接对运行时值进行编码。但是您可以接近以下模式

public void MyApi(SomeType type = null) {
  type = type ?? new SomeType();
  ...
}

Optional parameters are required to be constants because they are written out as values of an attribute. Hence they inherit all of the restrictions that an attribute value has.

There is no way to directly encode a runtime value. However you can get close with the following pattern

public void MyApi(SomeType type = null) {
  type = type ?? new SomeType();
  ...
}
瀟灑尐姊 2024-10-29 07:26:14

可选参数被编译到程序集中,因此(就像指定为 const 的任何内容一样)它们必须是编译时常量。

不,您不能使用执行时值作为可选参数。

Optional parameters are compiled into the assembly and as such (just like anything that is designated as const) they must be a compile-time constant.

And no, you cannot use execution-time values as optional parameters.

何时共饮酒 2024-10-29 07:26:14

可选参数在编译时确定,如果您调用参数太少的方法,则将其替换到方法中。它们是通过向方法的 IL 中的参数添加属性来处理的。

因此,它们需要在编译时完全解析(既用于创建,因为它们是属性,又用于使用时)。无法将运行时值用于可选方法参数。

Optional parameters are determined at compile time, and substituted into the method if you call a method with too few parameters. They are handled via adding an attribute to the parameter in the method's IL.

As such, they need to be fully resolved at compile time (both for creation, since they're an attribute, but also when used). There is no way to use runtime values for optional method parameters.

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