Is a public getter and a private setter with same name possible in C#?

前端 未结 6 1493
陌清茗
陌清茗 2021-02-06 21:29

How can I create a public getter and a private setter for a property? Is the following correct?

public String Password
{
    set { this._password = value; }
}

p         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 22:22

    Yes, as of C# 2.0, you can specify different access levels for the getter and the setter of a property.

    But you have the syntax wrong: you should declare them as part of the same property. Just mark the one you want to restrict with private. For example:

    public String Password
    {
        private get { return this._password; }
        set { this._password = value; }
    }
    

提交回复
热议问题