我了解可选参数,并且非常喜欢它们,但我想更多地了解如何将它们与继承的接口一起使用。
附件A
interface IMyInterface
{
string Get();
string Get(string str);
}
class MyClass : IMyInterface
{
public string Get(string str = null)
{
return str;
}
}
现在我会认为Get
中的方法MyClass
继承了接口的两个方法,但是......
“MyClass”未实现接口成员“MyInterface.Get()”
这有充分的理由吗?
也许我应该通过将可选参数放入您所说的界面中来解决此问题?但这又如何呢?
附件B
interface IMyInterface
{
string Get(string str= "Default");
}
class MyClass : IMyInterface
{
public string Get(string str = "A different string!")
{
return str;
}
}
这段代码编译得很好。但这不一定是正确的吗?然后通过更多的挖掘,我发现了这一点:
IMyInterface obj = new MyClass();
Console.WriteLine(obj.Get()); // writes "Default"
MyClass cls = new MyClass();
Console.WriteLine(cls.Get()); // writes "A different string!"
调用代码似乎是根据声明的对象类型获取可选参数的值,然后将其传递给方法。对我来说,这似乎有点愚蠢。也许可选参数和方法重载都有各自的使用场景?
我的问题
我的调用代码正在传递一个实例IMyInterface
并且需要在不同的点调用这两个方法。
我是否会被迫在每个实现中实现相同的方法重载?
public string Get()
{
return Get("Default");
}