真奇怪的是,在界面中爲可選參數放置的值實際上有所不同。我想你必須質疑這個值是一個接口細節還是一個實現細節。我會說後者,但事情就像前者一樣。例如,以下代碼輸出1 0 2 5 3 7。
// Output:
// 1 0
// 2 5
// 3 7
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
interface IMyOtherTest
{
void MyTestMethod(int notOptional, int optional = 7);
}
class MyTest : IMyTest, IMyOtherTest
{
public void MyTestMethod(int notOptional, int optional = 0)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
myTest1.MyTestMethod(1);
IMyTest myTest2 = myTest1;
myTest2.MyTestMethod(2);
IMyOtherTest myTest3 = myTest1;
myTest3.MyTestMethod(3);
}
}
}
是什麼樣有趣的是,如果你的界面使參數可選類實現它沒有這樣做:
// Optput:
// 2 5
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
class MyTest : IMyTest
{
public void MyTestMethod(int notOptional, int optional)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
// The following line won't compile as it does not pass a required
// parameter.
//myTest1.MyTestMethod(1);
IMyTest myTest2 = myTest1;
myTest2.MyTestMethod(2);
}
}
}
什麼似乎是一個錯誤,但是,如果你明確地實現了接口,你在類中爲可選值給出的值是毫無意義的。在以下示例中,如何使用值9?編譯時甚至沒有提示。
// Optput:
// 2 5
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
class MyTest : IMyTest
{
void IMyTest.MyTestMethod(int notOptional, int optional = 9)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
// The following line won't compile as MyTest method is not available
// without first casting to IMyTest
//myTest1.MyTestMethod(1);
IMyTest myTest2 = new MyTest();
myTest2.MyTestMethod(2);
}
}
}
Martin的評論下面給出了各種陷阱的詳細例子,我希望編譯器標記不匹配的默認參數。也就是說,我在我的代碼中使用了它,因爲它確實表明了我作爲開發人員在接口和實現級別爲其他開發人員查看的意圖。 – 2014-07-09 15:13:15
有趣的相關問題,「[是否有任何理由在接口中聲明可選參數?](https:// stackoverflow。com/questions/6752762 /)「,以及」[爲什麼C#4可選參數在接口上沒有被強制實施類?](https://stackoverflow.com/questions/4922714/)「,第二個有趣的[答案來自Lippert](https://stackoverflow.com/a/4923642/1028230)。 – ruffin 2017-09-07 16:55:41