c# - 可选参数和继承

标签 c# inheritance optional-parameters

我了解可选参数,而且我非常喜欢它们,但我只是想了解更多有关将它们与继承接口(interface)一起使用的信息。

图表 A

interface IMyInterface
{
    string Get();
    string Get(string str);
}

class MyClass : IMyInterface
{
    public string Get(string str = null)
    {
        return str;
    }
}

现在我会认为 MyClass 中的 Get 方法继承了接口(interface)的两个方法,但是...

'MyClass' does not implement interface member '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");
}

最佳答案

我也没有意识到,可选参数不会更改方法签名。所以下面的代码是完全合法的,实际上是我的解决方案:

interface IMyInterface
{
    string Get(string str = "Default");
}

class MyClass : IMyInterface
{
    public string Get(string str)
    {
        return str;
    }
}

因此,如果我有一个 MyClass 的实例,我必须调用 Get(string str),但如果该实例已被声明为基接口(interface) IMyInterface ,我仍然可以调用 Get(),它首先从 IMyInterface 获取默认值,然后调用该方法。

关于c# - 可选参数和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094616/

相关文章:

c# - 如何获取本地机器的 IPv4 和 IPv6 地址?

C# 泛型类型的声明

c++ - Friend 类及其所有后代

c# - 方法中的可选参数不是矩形的编译时常量错误

c# - 批量插入在 Azure SQL Server 中无法正常工作

c# - MessageBox 关闭后结束程序

python - 在 Python 中,派生类可以被截断为基类吗?

python - 类实例化以及抽象/静态类的变量共享

C# 可选参数 : Why can I define the default different on interface and derived class?

sql-server - 带有可选参数的 SQL Server 存储过程更新了错误的列