接口继承:是否可以扩展属性? [英] Interface inheritance: is extending properties possible?

查看:656
本文介绍了接口继承:是否可以扩展属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

interface IBase
{
    string Property1 { get; }
}

interface IInherited : IBase
{
    string Property1 { get; set; }
}

这样 IInherited 将具有继承的属性 Property1 ,并添加了允许设置的功能。

So that IInherited would have the inherited property Property1 with added functionality to allow set.

这可能吗?语法是什么?

Is that possible? What's the syntax?

编辑:请注意我将继承一词放在粗体字中。我具体要求继承该属性,而不是将其隐藏在新属性背后。

推荐答案

如果事实是唯一的方法是使用 new 关键字困扰你,然后我认为你认为接口错误。

If the fact that the only way to do this is by using the new keyword bothers you, then in my opinion you're thinking about interfaces wrong.

当然,你可以说 IInherited 继承自 IBase ;但这真的意味着什么?这些是接口;他们建立代码合同。隐藏 IBase.Property1 属性与新字符串Property1 {get;组; } ,你没有隐藏任何功能。因此,许多开发人员认为隐藏为坏事物的传统原因 - 它违反了多态性 - 在这种情况下无关紧要。

Sure, you could say that IInherited "inherits from" IBase; but what does that really mean? These are interfaces; they establish code contracts. By hiding the IBase.Property1 property with new string Property1 { get; set; }, you are not shadowing any functionality. Thus the traditional reason that a lot of developers consider hiding to be a "bad" thing -- that it violates polymorphism -- is irrelevant in this case.

问问自己:什么重要在接口方面?它们提供了对某些方法调用的响应的保证,对吗?

Ask yourself: what really matters when it comes to interfaces? They provide a guarantee of responding to certain method calls, right?

因此,给定以下两个接口:

So, given the following two interfaces:

interface IBase
{
    string Property1 { get; }
}

interface IInherited : IBase
{
    new string Property1 { set; }
}




  1. 如果对象实现 IBase ,你可以阅读它的 Property1 属性。

  2. 如果一个对象实现 IInherited ,您可以阅读其 Property1 属性(就像 IBase 实现一样),你也可以写信给它。

  1. If an object implements IBase, you can read its Property1 property.
  2. If an object implements IInherited, you can read its Property1 property (just as with an IBase implementation), and you can also write to it.

同样,这里确实没什么问题。

Again, there's really nothing problematic here.

这篇关于接口继承:是否可以扩展属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆