为什么我们必须命名接口方法参数? [英] Why do we have to name interface method parameters?
问题描述
在 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);
}
}
在这个实现中,在使用接口时,times
和lineBreaks
上都有默认参数,所以如果通过接口访问,可以使用默认值,不用命名参数,我们将无法跳过 times
参数而仅指定 lineBreaks
参数.
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.
仅供参考,根据您是通过接口还是通过类访问 Output
方法来确定默认参数是否可用,以及它们的值是什么.
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屋!