Geo*_*ett 21 c# parameters language-design interface
在C#中,我们必须命名接口方法的参数.
我明白,即使我们没有这样做,这样做也会有助于读者理解其含义,但在某些情况下并不是真的需要:
interface IRenderable
{
void Render(GameTime);
}
Run Code Online (Sandbox Code Playgroud)
我会说上面的内容与下面一样可读且有意义:
interface IRenderable
{
void Render(GameTime gameTime);
}
Run Code Online (Sandbox Code Playgroud)
是否有某些技术原因需要界面上方法参数的名称?
值得注意的是,接口方法的实现可以使用与接口方法中的名称不同的名称.
Luk*_*oid 19
一个可能的原因可能是使用可选参数.
如果我们使用接口,则无法指定命名参数值.一个例子:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在此实现,使用接口时,则对默认参数times和lineBreaks,所以如果通过接口访问,也可以使用默认设置,无需指定参数,我们将无法跳过times参数,并仅指定lineBreaks参数.
只是一个FYI,取决于您是Output通过接口还是通过类访问方法,确定默认参数是否可用,以及它们的值是什么.
Sco*_*pey 11
我认为没有任何理由可以将其作为技术要求.但我能想到一个特别好的理由:
如您所述,实现接口时不需要参数名称,可以轻松覆盖.
但是,在使用界面时,如果没有参数具有有意义的名称,请想象难度!没有intellisense,没有提示,只有一种类型?呸.
这必须是始终需要名称的最大原因.