Why do optional parameters in C# 4.0 require compile-time constants?

大憨熊 提交于 2019-12-03 17:09:32

问题


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


回答1:


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();
  ...
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5346786/why-do-optional-parameters-in-c-sharp-4-0-require-compile-time-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!