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

前端 未结 3 1655
野性不改
野性不改 2021-02-08 04:34

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

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 04:44

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

提交回复
热议问题