I'd like to have an
interface IFoo
{
string Foo { get; }
}
使用以下实现:
abstract class Bar : IFoo
{
string IFoo.Foo { get; private set; }
}
我希望该属性可以通过接口进行获取,但只能在具体实现中进行写入。如何最简单地实现?我需要手动实现getter和setter吗?
interface IFoo
{
string Foo { get; }
}
abstract class Bar : IFoo
{
public string Foo { get; protected set; }
}
IFoo.
并使用protected
。我建议使用protected
,假设你只想从派生类内部访问它。如果你想要完全公开(也可以在类外设置),只需使用:public string Foo { get; set; }
IFoo.Foo {get; protected set; }
,则编译器将会给出两个错误,但由于其中一个正在抱怨你甚至不应该有一个 setter,因此访问器问题有点无关紧要。 - juharr[<kbd>运行代码</kbd>](https://dotnetfiddle.net/U0GGIK)
的内容。这将在页面上创建一个“按钮”,供人们单击以运行您的示例。 - Scott Chamberlaininterface IFoo { string Foo { get; } }
abstract class Bar : IFoo { public string Foo { get; protected set; } }
可以将实现方式从显式变为隐式
abstract class Bar : IFoo
{
public string Foo { get; protected set; }
}
或者添加一个后备字段
abstract class Bar : IFoo
{
protected string _foo;
string IFoo.Foo { get { return _foo; } }
}
只需使用protected set
,并在属性前删除IFO
即可使其隐式。
interface IFoo
{
string Foo { get; }
}
abstract class Bar : IFoo
{
public string Foo { get; protected set; }
}
IFoo.Foo
。Ahmad 在我发表评论后更改了他的答案,但我的评论仍然正确。 - juharr
protected
是正确的选择。” - Jaystring PartitionKey { get; protected set; }
会产生一个错误:“接口中不能使用访问修饰符来定义访问器”。 - bfopsprotected
而不是在接口上使用。 - Jay