Why do we have to name interface method parameters?

后端 未结 5 1527
醉酒成梦
醉酒成梦 2021-01-03 21:52

In C# we have to name the parameters of a method of an interface.

I understand that even if we didn\'t have to, doing so would help a reader understand the meaning,

5条回答
  •  滥情空心
    2021-01-03 22:38

    One possible reason could be the use of optional parameters.

    If we were using an interface, it would be impossible to specify named parameter values. An example:

    interface ITest
    {
        void Output(string message, int times = 1, int lineBreaks = 1);
    }
    
    class Test : ITest
    {
    
        public void Output(string message, int numTimes, int numLineBreaks)
        {
            for (int i = 0; i < numTimes; ++i)
            {
                Console.Write(message);
                for (int lb = 0; lb < numLineBreaks; ++lb )
                    Console.WriteLine();
            }
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            ITest testInterface = new Test();
            testInterface.Output("ABC", lineBreaks : 3);
        }
    }
    

    In this implementation, when using the interface, there are default parameters on times and lineBreaks, so if accessing through the interface, it is possible to use defaults, without the named parameters, we would be unable to skip the times parameter and specify just the lineBreaks parameter.

    Just an FYI, depending upon whether you are accessing the Output method through the interface or through the class determines whether default parameters are available, and what their value is.

提交回复
热议问题