使用接口时如何实现私有setter
本文关键字:实现 setter 接口 何实现 | 更新日期: 2023-09-27 18:27:57
我创建了一个具有一些属性的接口。
如果接口不存在,类对象的所有属性都将设置为
{ get; private set; }
然而,当使用接口时,这是不允许的,所以这可以实现吗?如果可以,如何实现?
在界面中,您只能为属性定义getter
interface IFoo
{
string Name { get; }
}
但是,在您的类中,您可以将其扩展为具有private setter
-
class Foo : IFoo
{
public string Name
{
get;
private set;
}
}
接口定义公共API。若公共API只包含getter,那个么在接口中只定义getter:
public interface IBar
{
int Foo { get; }
}
私有setter不是公共api的一部分(和任何其他私有成员一样),因此您不能在接口中定义它。但是您可以自由地向接口实现添加任何(私有)成员。事实上,setter是作为公共的还是私有的,或者是否会有setter:,都无关紧要
public int Foo { get; set; } // public
public int Foo { get; private set; } // private
public int Foo
{
get { return _foo; } // no setter
}
public void Poop(); // this member also not part of interface
Setter不是接口的一部分,因此不能通过您的接口调用:
IBar bar = new Bar();
bar.Foo = 42; // will not work thus setter is not defined in interface
bar.Poop(); // will not work thus Poop is not defined in interface