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

前端 未结 6 1487
陌清茗
陌清茗 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:14

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

    MSDN:

    The get and set methods are generally no different from other methods. They can perform any program logic, throw exceptions, be overridden, and be declared with any modifiers allowed by the programming language.

    Edit: MSDN quote is just to clarify why geter and setter can have different access mdofiers, Good point raised by @Cody Gray:

    Yes, properties can perform program logic and throw exceptions. But they shouldn't. Properties are intended to be very lightweight methods, comparable to accessing a field. The programmer should expect to be able to use them as they would a field without any noticeable performance implications. So too much heavy program logic is strongly discouraged. And while setters can throw exceptions if necessary, getters should almost never throw exceptions

提交回复
热议问题