C# public variable as writeable inside the class but readonly outside the class

后端 未结 9 1689
说谎
说谎 2020-12-09 14:52

I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don\'t want the

相关标签:
9条回答
  • 2020-12-09 15:18

    Sure. Make it a property, and make the setter private:

    public Int32 SomeVariable { get; private set; }
    

    Then to set it (from within some method in the class):

    SomeVariable = 5;
    
    0 讨论(0)
  • 2020-12-09 15:21

    Use a private variable and expose a public property.

    class Person
    {
      private string name;
    
      public string Name
      {
        get
        {
          return name;
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-09 15:22

    Define it as private? Is that what you asking for, you can modify it any where inside the container class but you can't out side it

    0 讨论(0)
提交回复
热议问题