Best way to expose protected fields

前端 未结 6 997
不知归路
不知归路 2021-01-19 05:50

I have a base class like this:

 public class BaseModalCommand
 {

    protected object m_commandArgument;
    protected int m_commandID;
    protected int m_         


        
6条回答
  •  爱一瞬间的悲伤
    2021-01-19 05:50

    As best practice, your class fields should be marked as private and wrapped in a getter/setter property

    so instead of

    protected object m_commandArgument;
    

    use

    private object m_commandArgument;
    
    protected object CommandArgument {get; set;}
    

    Theres several advantages to this but a simple usage would be exception handling/validation in your setter.

    e.g.

    private string _email;
    protected string Email
    { 
       get { return _email; }
       set 
       {
           if(value.IndexOf("@") > 0)
               _email = value;
           else
                throw new ArgumentException("Not a valid Email");
       }
    }
    

提交回复
热议问题