为什么C#编译器不会允许私有属性setter的接口? [英] Why C# compiler does not allows private property setters in interfaces?
问题描述
在某些情况下像一个MVVM视图模型,我有时需要有私人二传手的视图模型公开,只能在内部修改的状态。
所以,这是错的需要在接口上的私人二传手? (我的意思并不是特别是在描述的场景)如果不是,为什么C#编译器不允许呢?
感谢。
< DIV CLASS =h2_lin>解决方案
根据定义,接口是其它代码使用,而不是为私有成员的合同。但是,您可以在接口指定只读属性,并落实在具体的类的私人二传手:
公共接口IFoo的
{
串MyReadonlyString {搞定; }
}
公共类FooImplementation:IFoo的
{
公共字符串MyReadonlyString {搞定;私人集; }
}
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.
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?
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:
public interface IFoo
{
string MyReadonlyString { get; }
}
public class FooImplementation : IFoo
{
public string MyReadonlyString { get; private set; }
}
这篇关于为什么C#编译器不会允许私有属性setter的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!