为什么我们命名接口方法的参数? [英] Why do we have to name interface method parameters?

查看:104
本文介绍了为什么我们命名接口方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我们必须命名一个接口的方法的参数。

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?

值得注意的是,接口方法的实现可以使用不同的名称那些在接口的方法。

推荐答案

一个可能的原因可能是使用可选参数。

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.

这篇关于为什么我们命名接口方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆