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

限于喜欢 提交于 2019-12-03 01:08:16

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".)

I interpret your question to be about Optional Arguments.

If so then I believe they are CLS-Compliant and you can check by using the CLSCompliant attribute:

using System;

[assembly: CLSCompliant(true)]

namespace ConsoleApplication1
{
    public class Program
    {
        public static int Test(int val=42)
        {
            return val;
        }

        static void Main(string[] args)
        {
            System.Console.WriteLine(Test());
        }
    }
}

This compiles with no warnings.

Have a look at the CLS specs.
From page 41:

The vararg constraint can be included to indicate that all arguments past this point are optional. When it appears, the calling convention shall be one that supports variable argument lists.

But the box right below says:

CLS Rule 15: The vararg constraint is not part of the CLS, and the only calling convention supported by the CLS is the standard managed calling convention

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