What is the purpose of the “get” and “set” properties in C#

前端 未结 7 1543
鱼传尺愫
鱼传尺愫 2020-12-30 12:35

I saw some get set method to set values. Can anyone tell me the purpose of this?

public string HTTP_USER_NAME
{
      get 
      {
            return UserNam         


        
相关标签:
7条回答
  • 2020-12-30 13:11

    It seems as though you understand the functionality of getters and setters, and others answered that question. "Normal" class variables (without getters and setters) are called "fields", and "properties" (which have the getters and setters) encapsulate fields.

    The purpose of properties is to control outside access to fields. If you want a variable to be read-only to outside logic, you can omit the setters, like so:

    private int dataID;
    
    public int DataID {
        get { return dataID; }
    }
    

    You can also make the setter private and achieve the same read-only functionality.

    If an object has a chance of being null (for whatever reason), you can guarantee an instance always exists like this:

    private Object instance;
    
    public Object Instance {
        get {
            if (instance == null)
                instance = new Object();
            return instance;
        }
    }
    

    Another use for properties is defining indexers.

    //in class named DataSet
    
    private List<int> members;
    
    public int this[int index] {
        get { return members[index]; }
    }
    

    With that indexer defined, you can access an instance of DataSet like this:

    int member = dataSet[3];
    
    0 讨论(0)
提交回复
热议问题