Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - Why do we have to name interface method parameters?

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, however in some cases it's not really needed:

interface IRenderable
{
    void Render(GameTime);
}

I would say the above is as readable and meaningful as the below:

interface IRenderable
{
    void Render(GameTime gameTime);
}

Is there some technical reason why names for parameters of methods on an interface are required?


It's worth noting that the implementation of the interface method can use different names to those in the interface's method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...