Mal*_*lki 25 c# inheritance properties interface
我想做这个:
interface IBase
{
string Property1 { get; }
}
interface IInherited : IBase
{
string Property1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
因此,这IInherited
将具有允许添加功能的继承属性.Property1
set
那可能吗?语法是什么?
编辑:请注意我把"继承"这个词放在粗体字中.我具体要求继承该属性,而不是将其隐藏在新属性背后.
Dan*_*Tao 24
如果这样做的唯一方法就是使用new
关键字困扰你,那么在我看来,你认为接口是错误的.
当然,你可以说IInherited
"继承自" IBase
; 但这究竟意味着什么?这些是接口; 他们建立代码合同.通过隐藏IBase.Property1
属性new string Property1 { get; set; }
,您不会隐藏任何功能.因此,许多开发人员认为隐藏为"坏"事物的传统原因 - 它违反了多态性 - 在这种情况下无关紧要.
问问自己:接口界面真正重要的是什么?它们提供了对某些方法调用的响应保证,对吧?
因此,给定以下两个接口:
interface IBase
{
string Property1 { get; }
}
interface IInherited : IBase
{
new string Property1 { set; }
}
Run Code Online (Sandbox Code Playgroud)
IBase
,您可以读取其Property1
属性.IInherited
,你可以读取它的Property1
属性(就像IBase
实现一样),你也可以写它.再说一次,这里真的没什么问题.
无论如何,你的代码应该可以工作......它只是因为隐藏 Property1 而创建了一个编译器警告。要使用新前缀清除 IInherited 中的此警告标记 Property1