【问题标题】:Read-only interface property that's read/writeable inside the implementation在实现中可读取/可写入的只读接口属性
【发布时间】:2014-11-15 05:26:47
【问题描述】:

我想要一个

interface IFoo
{
    string Foo { get; }
}

实现如下:

abstract class Bar : IFoo
{
    string IFoo.Foo { get; private set; }
}

我希望属性可以通过接口获取,但只能在具体实现中写入。最干净的方法是什么?我是否需要“手动”实现 getter 和 setter?

【问题讨论】:

  • protected 是要走的路。
  • 你能澄清一下吗? string PartitionKey { get; protected set; } 产生错误“可访问性修饰符不能用于接口中的访问器”
  • 您需要使用支持字段来实现该属性 - 然后您就可以从具体实现中访问该字段(当设置为受保护时)。我认为您无法使用自动属性来实现这一点。
  • 具体类中刚刚设置的使用有什么问题?然后你就可以读写了。
  • class 上使用protected 而不是interface

标签: c# interface


【解决方案1】:
interface IFoo
{
    string Foo { get; }
}


abstract class Bar : IFoo
{
    public string Foo { get; protected set; }
}

几乎和你一样,但 protected 并从类中的属性中删除 IFoo.

我建议protected 假设您只想从派生类内部访问它。相反,如果您希望它完全公开(也可以在类之外设置),只需使用:

public string Foo { get; set; }

【讨论】:

  • 啊,太好了,谢谢!我认为Bar 中的属性必须是IFoo.Foo,这给了我错误。
  • 但它给出了错误“访问器必须更具限制性......”
  • @Stewart_R DotNetFiddle works even better 用于展示工作代码示例。
  • @Ahmad 如果它在显式和受保护的IFoo.Foo {get; protected set; } 处编译器将给出两个错误,但由于一个抱怨你甚至不应该有一个setter,所以访问器问题有点没有意义。跨度>
  • @Stewart_R 想学习第二个最有用的东西吗?在您的答案中,在您的代码示例下方添加类似于[<kbd>Run Code</kbd>](https://dotnetfiddle.net/U0GGIK) 的内容。它在页面上创建了一个“按钮”,人们可以单击以运行您的示例。
【解决方案2】:

为什么要显式实现接口?这编译和工作没有问题:

interface IFoo { string Foo { get; } }
abstract class Bar : IFoo { public string Foo { get; protected set; } }

否则,您可以拥有该类的受保护/私有属性,并显式实现接口,但将 getter 委托给类的 getter。

【讨论】:

    【解决方案3】:

    要么使实现隐式而不是显式

    abstract class Bar : IFoo
    {
        public string Foo { get; protected set; }
    }
    

    或者添加一个支持字段

    abstract class Bar : IFoo
    {
        protected string _foo;
        string IFoo.Foo { get { return _foo; } }
    }
    

    【讨论】:

      【解决方案4】:

      只需使用protected set 并删除属性前的IFO 以使其隐式。

      interface IFoo
      {
          string Foo { get; }
      }
      abstract class Bar : IFoo
      {
          public string Foo { get; protected set; }
      }
      

      【讨论】:

      • 因为这是一个显式实现,所以不能添加 setter。
      • @juharr 嗯?伙计们,这不是真的!以上代码不会产生任何错误:i.imgur.com/sLcXpeh.png
      • @Stewart_R 那是因为你没有明确的实现IFoo.Foo。自从我发表评论后,艾哈迈德改变了他的答案,这仍然是正确的。
      • @juharr 这个问题有点模棱两可,我认为 OP 意味着其他人注意到的受保护属性,但它也可能意味着具体实现的读/写属性(而不是在实现内部)
      猜你喜欢
      • 2010-11-22
      • 2010-09-26
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2019-04-20
      • 2014-10-20
      • 2013-01-15
      相关资源
      最近更新 更多