开发者

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

开发者 https://www.devze.com 2023-04-12 20:04 出处:网络
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.

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?开发者_C百科 (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; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号