gpt4 book ai didi

c# - 可选参数和继承

转载 作者:太空狗 更新时间:2023-10-29 21:59:11 26 4
gpt4 key购买 nike

我了解可选参数,而且我非常喜欢它们,但我只是想了解更多有关将它们与继承接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com