gpt4 book ai didi

c# - 如何在 C# 中使继承的不可变属性可变?

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:03 24 4
gpt4 key购买 nike

假设我有一个包含以下属性的接口(interface)

interface IFoo
{
Int32 Id { get; }
}

现在假设我想创建一个 IMutableFoo 接口(interface)。从逻辑上讲,我认为以下是正确的:

interface IMutableFoo: IFoo
{
Int32 Id { set; }
}

我的想法是它会继承 Id,然后在我的子界面中让它可设置。令我惊讶的是,这没有用。相反,我收到一条警告,让我知道我实际上正在用 IMutableFoo 中的 Id 覆盖 IFoo 中的 Id。我试着改变 { set; } 要得到;放; } 结果相同。我该怎么做?在 Java 中,我会简单地添加一个 setId 方法。我如何在 C# 中执行此操作?谢谢!

最佳答案

除了定义一个具有新读/写属性的新接口(interface)之外,您无能为力。这是因为在谈论接口(interface)时没有继承的概念;相反,像IMutableFoo 这样的接口(interface)是一个 promise ,它的实现者也将实现接口(interface)IFoo。然而,这两个接口(interface)都是独立定义的,并且保持独立。

MSDN documentation包含短语“接口(interface)可以继承其他接口(interface)”,但恕我直言,这是一种误导,因为这里没有继承。 “派生”接口(interface)简单地描述了比“基本”接口(interface)必须实现的更大的成员集。

IMutableFoo 等接口(interface)的实现者可以通过显式实现 IFoo 并在 IMutableFoo.Id 的 getter 之间共享代码来毫无问题地提供您的目标语义IFoo.Id:

class Foo : IMutableFoo {
// IFoo is implemented explicitly
// "this" is of type Foo, and since IMutableFoo is implemented
// implicitly below, this.Id accesses the Id declared in IMutableFoo
Int32 IFoo.Id { get { return this.Id; } }

// IMutableFoo is implemented implicitly
// It could also be implemented explicitly, but the body of the
// IFoo.Id getter would need to change ("this" would no longer work)
public Int32 Id { get; set; }
}

不幸的是,没有强制实现者这样做的机制,但是一些好的文档在这里可以发挥很大的作用——如果 IFoo 和之间的关系更是如此IMutableFoo 很直观。

关于c# - 如何在 C# 中使继承的不可变属性可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875552/

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