简体   繁体   English

为什么C#编译器不允许接口中的私有属性设置器?

[英]Why C# compiler does not allows private property setters in interfaces?

In certain scenario like a MVVM view-model, I sometimes needs to have private setter as the view-model exposes a state that can only be modified internally. 在某些情况下,比如MVVM视图模型,我有时需要私有setter,因为视图模型公开了一个只能在内部修改的状态。

So is this wrong to need a private setter on an interface? 那么在接口上需要私有的setter是错误的吗? (and I mean not particularly in the described scenario) If not, why does the C# compiler does not allow it? (我的意思不是特别在所描述的场景中)如果没有,为什么C#编译器不允许它?

Thanks. 谢谢。

By definition, an interface is a contract for other code to use, not for private members. 根据定义,接口是其他代码使用的合同,而不是私有成员的合同。 However, you can specify read-only properties in interfaces and implement a private setter in the concrete class: 但是,您可以在接口中指定只读属性,并在具体类中实现私有setter:

public interface IFoo
{
    string MyReadonlyString { get; }
} 

public class FooImplementation : IFoo
{
    public string MyReadonlyString { get; private set; }
}

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

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