简体   繁体   English

在实现中可读/写的只读接口属性

[英]Read-only interface property that's read/writeable inside the implementation

I'd like to have an 我想要一个

interface IFoo
{
    string Foo { get; }
}

with an implementation like: 实现如下:

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

I'd like the property to be gettable through the interface, but only writable inside the concrete implementation. 我希望通过接口可以获取属性,但只能在具体实现中写入。 What's the cleanest way to do this? 最干净的方法是什么? Do I need to "manually" implement the getter and setter? 我需要“手动”实现getter和setter吗?

interface IFoo
{
    string Foo { get; }
}


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

almost as you had it but protected and drop the IFoo. 几乎和你一样,但protected并放弃了IFoo. from the property in the class. 来自班上的财产。

I suggest protected assuming you only want it accessable from INSIDE the derived class. 我建议protected假设你只想从INSIDE派生类访问它。 If, instead, you'd want it fully public (able to be set outside the class too) just use: 相反,如果你想要它完全公开(也可以在课外设置),只需使用:

public string Foo { get; set; }

Why the explicit implementation of the interface? 为什么显式实现接口? This compiles and works without problems: 这编译和工作没有问题:

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

Otherwise, you could have a protected/private property for the class, and implement the interface explicitly, but delegate the getter to the class's getter. 否则,您可以拥有该类的protected / private属性,并显式实现该接口,但将getter委托给类的getter。

Either make the implementation implicit instead of explicit 要么实现隐式而不是显式

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

Or add a backing field 或者添加支持字段

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

Just use protected set and also remove the IFO before the property to make it implicit. 只需使用protected set并在属性之前删除IFO以使其隐式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM