为什么 C# 4.0 中的可选参数需要编译时常量?
还有一种方法可以使用可选方法参数的运行时值吗?
Also is there a way to use run-time values for optional method parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
还有一种方法可以使用可选方法参数的运行时值吗?
Also is there a way to use run-time values for optional method parameters?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
可选参数必须是常量,因为它们是作为属性值写出的。因此,它们继承了属性值所具有的所有限制。
无法直接对运行时值进行编码。但是您可以接近以下模式
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
可选参数被编译到程序集中,因此(就像指定为 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.
可选参数在编译时确定,如果您调用参数太少的方法,则将其替换到方法中。它们是通过向方法的 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.