When should you use a field rather than a property?

前端 未结 7 1970
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 06:56

Can anyone clearly articulate when you use a field and when to use a property in class design?

Consider:

public string Name;

Or:

7条回答
  •  一生所求
    2020-12-06 06:57

    Using properties you can control it's security:

    public string Foo { protected get; private set; }
    

    Properties gives easy way to raise events:

    public string Foo
    {
      get { return _foo; }
    }
    set
    {
      bool cancel = false;
      if(BeforeEvent != null) // EventHandler BeforeEvent
      {
        CancelEventArgs e = new CancelEventArgs();
        BeforeEvent(this, e);
        cancel = e.Cancel;
      }
      if(!cancel)
      {
        _foo = value;
        if(AfterEvent != null) // EventHandler AfterEvent
        {
          AfterEvent(this, new EventArgs());
        }
      }
    }
    

    Also I often use code like this:

    string Foo
    {
      set
      {
        IsFooSet = value != null;
      }
    }
    
    bool IsFooSet
    {
      get { return _isFoo; }
      set
      { 
       _isFoo = value;
       if(value) // some event raise or controls on form change
      }
    }
    

提交回复
热议问题