Is the new feature of C# 4.0 - “Optional Parameters” CLS-Compliant?

后端 未结 3 793
生来不讨喜
生来不讨喜 2021-02-05 02:51

This new feature is really convenient.

Lately I read the document of the \"Microsoft All-In-One Code Framework\", and it mentions that \"Optional Parameters\" is not CLS

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 03:27

    Optional arguments are "sort-of" CLS-compliant. Methods with optional arguments are legal and can be successfully compiled with the CLSCompliant attribute, but callers of those methods don't necessarily need to take account of the default parameter values or the optional attribute. (In which case those methods would behave in exactly the same way as standard methods, requiring that all the arguments be stated explicitly at the call site.)

    Methods that use default parameters are allowed under the Common Language Specification (CLS); however, the CLS allows compilers to ignore the values that are assigned to these parameters. Code that is written for compilers that ignore default parameter values must explicitly provide arguments for each default parameter. To maintain the behavior that you want across programming languages, methods that use default parameters should be replaced with method overloads that provide the default parameters.

    (Taken from the documentation for "CA1026: Default parameters should not be used".)

提交回复
热议问题