为什么 C# 编译器不允许接口中的私有属性设置器? [英] Why C# compiler does not allows private property setters in interfaces?

查看:15
本文介绍了为什么 C# 编译器不允许接口中的私有属性设置器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,例如 MVVM 视图模型,我有时需要私有 setter,因为视图模型公开只能在内部修改的状态.

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.

那么在接口上需要一个私有的 setter 是错误的吗?(我的意思不是特别在描述的场景中)如果不是,为什么 C# 编译器不允许它?

So is this wrong to need a private setter on an interface? (and I mean not particularly in the described scenario) If not, why does the C# compiler does not allow it?

谢谢.

推荐答案

根据定义,接口是供其他代码使用的契约,而不是供私有成员使用的契约.但是,您可以在接口中指定只读属性并在具体类中实现私有 setter:

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:

public interface IFoo
{
    string MyReadonlyString { get; }
} 

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

这篇关于为什么 C# 编译器不允许接口中的私有属性设置器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆