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

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

    public string Password { get; private set; }

    0 讨论(0)
  • 2021-02-06 22:09

    To gain an 'Excavator' badge, and to make the answer up to date - readonly fields encapsulated by a get-only property

    private readonly int myVal;
    public int MyVal get { return myVal; }
    

    may be now (as of C# 6.0) shortened to

    public int MyVal { get; }
    
    0 讨论(0)
  • 2021-02-06 22:14
    public String Password
    {
        private set { this._password = value; }
        get { return this._password; }
    }
    

    or you can use an auto-implemented property:

    public String Password { get; private set; }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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; }
    }
    
    0 讨论(0)
  • 2021-02-06 22:24

    Yes it is possible, even with auto properties. I often use:

    public int MyProperty { get; private set; }
    
    0 讨论(0)
提交回复
热议问题