Why we need Properties in C#

前端 未结 8 1210
萌比男神i
萌比男神i 2020-12-01 09:31

Can you tell me what is the exact usage of properties in C# i mean practical explanation

in our project we are using properties like

/// 

        
8条回答
  •  情书的邮戳
    2020-12-01 10:33

    Think about it : You have a room for which you want to regulate who can come in to keep the internal consistency and security of that room as you would not want anyone to come in and mess it up and leave it like nothing happened. So that room would be your instantiated class and properties would be the doors people come use to get into the room. You make proper checks in the setters and getters of your properties to make sure any unexpected things come in and leave.

    More technical answer would be encapsulation and you can check this answer to get more information on that: https://stackoverflow.com/a/1523556/44852

    class Room {
       public string sectionOne;
       public string sectionTwo;
    }
    
    Room r = new Room();
    r.sectionOne = "enter";
    

    People is getting in to sectionOne pretty easily, there wasn't any checking.

    class Room 
    {
       private string sectionOne;
       private string sectionTwo;
    
       public string SectionOne 
       {
          get 
          {
            return sectionOne; 
          }
          set 
          { 
            sectionOne = Check(value); 
          }
       }
    }
    
    Room r = new Room();
    r.SectionOne = "enter";
    

    now you checked the person and know about whether he has something evil with him.

提交回复
热议问题