可选参数和inheritance
我理解可选参数,我非常喜欢它们,但我想更多地了解如何使用inheritance接口。
图表A
interface IMyInterface { string Get(); string Get(string str); } class MyClass : IMyInterface { public string Get(string str = null) { return str; } }
现在我认为MyClass
中的Get
方法inheritance了接口的两个方法,但是……
‘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"); }
我还没有意识到,可选参数不会改变方法签名 。 所以下面的代码完全合法,实际上是我的解决方案:
interface IMyInterface { string Get(string str = "Default"); } class MyClass : IMyInterface { public string Get(string str) { return str; } }
所以,如果我有MyClass
的实例,我必须调用Get(string str)
,但如果该实例已被声明为基本接口IMyInterface
,我仍然可以调用Get()
,它首先从IMyInterface
获取默认值,然后调用方法。
- 处理负时间跨度
- 如何将C#散列字节数组转换为字符串以传递给API?
- C#:GPS跟踪系统
- 在Using Block中调用Environment.Exit()
- 如何使用Json.Net序列化/反序列化具有其他属性的自定义集合
- 结构类型数组的性能
- System.Security.SecurityException:请求类型为’System.Security.Permissions.EnvironmentPermission,mscorlib’的权限失败
- 我应该使用Multiple RegularExpression属性吗?
- 在.NET应用程序中使用PCL时,如果被调用的类包含方法,则为TypeLoadException